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) {
        
    }];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章