關(guān)于單元測試的異步測試,需要通過名為XCTestExpectation的類來實現(xiàn)
相關(guān)方法
@interface XCTestCase (AsynchronousTesting)
- (XCTestExpectation *)expectationWithDescription:(NSString *)description;
@end
該方法生成一個XCTestExpectation對象,并為其賦值一個description參數(shù),文檔中對該參數(shù)的解釋是
* @param description
* This string will be displayed in the test log to help diagnose failures.
即該參數(shù)將會在測試Log中打印出來方便測試者查看測試結(jié)果。
也可以理解為超時錯誤提示,因為只有在異步操作時間超過了預(yù)設(shè)時間時才會在Log中打印出來。
@interface XCTestExpectation : NSObject
- (void)fulfill;
@end
該方法用于表示這個異步測試結(jié)束了,每一個XCTestExpectation都需要對應(yīng)一個fulfill,否則將會導(dǎo)致測試失敗,實際使用請看下面的例子。
- example:
- (void)testExpectation{
XCTestExpectation* expect = [self expectationWithDescription:@"Oh, timeout!"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(2); //延遲兩秒向下執(zhí)行
XCTAssert(YES,"Some Error Info");//通過測試
[expect fulfill];//告知異步測試結(jié)束
});
[self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
//等待10秒,若該測試未結(jié)束(未收到 fulfill方法)則測試結(jié)果為失敗
//Do something when time out
}];
}
分析:
1.該測試中,創(chuàng)建了一個XCTestExpectation對象,名為expect
2.通過GCD在全局隊列中開始一個異步動作,該動作的內(nèi)容為:
- 延遲2秒,判斷YES是否為YES,發(fā)送消息告知異步測試結(jié)束
3.通過waitForExpectationsWithTimeout:handler:做了兩件事
- 設(shè)置異步測試的時間長度,當(dāng)超過時間時,報測試錯誤,并打印預(yù)設(shè)的超時錯誤信息
- 超時發(fā)生時執(zhí)行block中的方法
該測試的結(jié)果應(yīng)該是Success
若想了解單元測試入門內(nèi)容,請移步這里
iOS單元測試(作用及入門提升)