美文网首页iOS精品文章-单元测试iOS 开发 iOS Developer
简单iOS单元测试-异步测试(XCTestExpectation

简单iOS单元测试-异步测试(XCTestExpectation

作者: 码痞 | 来源:发表于2016-08-31 13:37 被阅读1542次

关于单元测试的异步测试,需要通过名为XCTestExpectation的类来实现

相关方法
@interface XCTestCase (AsynchronousTesting)

- (XCTestExpectation *)expectationWithDescription:(NSString *)description;
@end

该方法生成一个XCTestExpectation对象,并为其赋值一个description参数,文档中对该参数的解释是
* @param description
* This string will be displayed in the test log to help diagnose failures.

即该参数将会在测试Log中打印出来方便测试者查看测试结果。
也可以理解为超时错误提示,因为只有在异步操作时间超过了预设时间时才会在Log中打印出来。


@interface XCTestExpectation : NSObject 

- (void)fulfill;
@end

该方法用于表示这个异步测试结束了,每一个XCTestExpectation都需要对应一个fulfill,否则将会导致测试失败,实际使用请看下面的例子。


  • example:
- (void)testExpectation{
   XCTestExpectation* expect = [self expectationWithDescription:@"Oh, timeout!"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        sleep(2); //延迟两秒向下执行
        XCTAssert(YES,"Some Error Info");//通过测试
        [expect fulfill];//告知异步测试结束
    });

    [self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
      //等待10秒,若该测试未结束(未收到 fulfill方法)则测试结果为失败
      //Do something when time out
    }];
}

分析:
1.该测试中,创建了一个XCTestExpectation对象,名为expect
2.通过GCD在全局队列中开始一个异步动作,该动作的内容为:

  • 延迟2秒,判断YES是否为YES,发送消息告知异步测试结束

3.通过waitForExpectationsWithTimeout:handler:做了两件事

  • 设置异步测试的时间长度,当超过时间时,报测试错误,并打印预设的超时错误信息
  • 超时发生时执行block中的方法

该测试的结果应该是Success

若想了解单元测试入门内容,请移步这里
iOS单元测试(作用及入门提升)

相关文章

网友评论

    本文标题:简单iOS单元测试-异步测试(XCTestExpectation

    本文链接:https://www.haomeiwen.com/subject/ahvqettx.html