IOS XCTest使用异步测试

XCTest使用异步测试需要用到XCTestExpectation这个类,

  1. 首先在测试方法中创建一个XCTestExpectation对象expectation
XCTestExpectation* exception = [self expectationWithDescription:@"xx"];
  1. 然后执行自定义的异步方法。在这里测试使用dispatch_async执行异步操作,真实的测试环境可能是执行一个异步的网络请求,在异步任务执行完成之后需要调用XCTestExpectation对象expectationfullfill方法,网络请求中需要再网络请求完成之后调用该方法。
    dispatch_queue_t queue = dispatch_queue_create("group.queue", DISPATCH_QUEUE_SERIAL);

    dispatch_block_t block = dispatch_block_create(0, ^{
        [NSThread sleepForTimeInterval:1.0f];
        printf("=====block invoke=====\n");
        [expectation fulfill];
    });

    dispatch_async(queue, block);
  1. 调用waitForExpectationsWithTimeout:handler方法传递一个时间参数和超时处理的block。
[self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {

    }];

完整的代码

- (void)testAsync {
    XCTestExpectation* expectation = [self expectationWithDescription:@"xx"];
    
    dispatch_queue_t queue = dispatch_queue_create("group.queue", DISPATCH_QUEUE_SERIAL);
    
    dispatch_block_t block = dispatch_block_create(0, ^{
        [NSThread sleepForTimeInterval:1.0f];
        printf("=====block invoke=====\n");
        [expectation fulfill];
    });
    
    dispatch_async(queue, block);
    
    [self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
        
    }];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容