iOS异步单元测试简单例子

2017-06-15  本文已影响0人  momirror

新手,一点笔记。

//期望测试,可以在异步执行结束后决定是否调用fullfill来通过测试。
- (void)testExpectation {
    
    //Description会在test出错时打印在控制台,方便跟踪。
    XCTestExpectation *expectation = [self expectationWithDescription:@"High Expectations"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        XCTAssertTrue(true);
        [expectation fulfill];
    });
  
    //如果没有fullfill或者超时,都会失败。
    [self waitForExpectationsWithTimeout:5.0 handler:nil];
}

//notification测试
- (void)testNotification {
    
    [self expectationForNotification:@"TestNotification"
                              object:nil
                             handler:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:nil];
    });
    
    [self waitForExpectationsWithTimeout:2.0 handler:nil];
}

//谓词测试
- (void)testPredicate {
    
    NSString * str = @"haha";
    NSPredicate *
    predicate = [NSPredicate predicateWithBlock:^BOOL(id  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        //返回值true/false决定是否测试成功,在这里写要测试的代码。
        NSString * str = evaluatedObject;
        return [str isEqualToString:@"haha"];
    }];
    
    //这里的str参数,可以在上面的block中读取(evaluatedObject)。
    [self expectationForPredicate:predicate
              evaluatedWithObject:str
                          handler:nil];
    
    [self waitForExpectationsWithTimeout:2.0 handler:nil];
}

//KVO测试
- (void)testKVO {
    
    UILabel * label = [[UILabel alloc] init];
    label.text = @"hello";
    
    //最后一个参数(@"nihao")为期望的kvo结果值,如果为空,则在值第一次变化时调用fullfill来通过测试。
     [self keyValueObservingExpectationForObject:label keyPath:@"text" expectedValue:@"nihao"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        label.text = @"nihao";
    });
    [self waitForExpectationsWithTimeout:5.0 handler:nil];
    
}```
上一篇下一篇

猜你喜欢

热点阅读