IOS XCTest使用异步测试

来源:互联网 发布:微机室上网控制软件 编辑:程序博客网 时间:2024/09/21 06:35

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) {            }];}
原创粉丝点击