XCTest使用異步測試需要用到XCTestExpectation
這個類,
- 首先在測試方法中創建一個
XCTestExpectation
對象expectation
。
XCTestExpectation* exception = [self expectationWithDescription:@"xx"];
- 然後執行自定義的異步方法。在這裏測試使用
dispatch_async
執行異步操作,真實的測試環境可能是執行一個異步的網絡請求,在異步任務執行完成之後需要調用XCTestExpectation
對象expectation
的fullfill
方法,網絡請求中需要再網絡請求完成之後調用該方法。
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);
- 調用
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) {
}];
}