UnitTests文件內容
@interface ViewControllerTest : XCTestCase
@property (nonatomic, strong) ViewController *vc;
@end
@implementation ViewControllerTest
- (void)setUp {
// 初始化…
self.vc = [[ViewController alloc] init];
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
// 銷毀…
self.vc = nil;
}
// 測試方法
- (void)testExample {
}
@end
UnitTests作用 :
1)幫助開發(fā),節(jié)省時間:無需走UI轉換流,可以直接到任意界面去測試;
2)檢查架構合理性: 如果測試很難寫,證明 當前結構 不太優(yōu)秀。
測試三部曲:
1: 準備數(shù)據(jù);
2: 調用方法;
3: 斷言結果, 判斷查看結果
// 準備數(shù)據(jù)
int num1 = 100;
int num2 = 200;
// 調用方法;
int sum = [self.Vc getPlusSum: num1 number2: num2 ];
// 斷言結果;
XCTAssertEqual( sum, “300”, “錯了錯了啊”);
書寫格式:
方法名必須 以 “test” 開頭
文件執(zhí)行順序:
- (void) setUp {
}
- (void)tearDown {
}
- (void)testFunc1 {
}
- (void)testFunc2 {
}
// 執(zhí)行順序
setUp
testFunc1
tearDown
setUp
testFunc2
tearDown
按測試目的 有哪些種類?
## 1)邏輯測試
- (void)testExample {
// 1000 + 2000 = 3000?
// 準備數(shù)據(jù)
int num1 = 1000;
int num2 = 2000;
// 調用方法;
int num3 = [self.vc getPlusSum:num1 num2:num2];
// 斷言結果;判斷查看結果
XCTAssertEqual(num3, 3000, @“草,結果不對了?。 ?;
}
## 2) 異步測試
- (void)testAsy {
// 準備數(shù)據(jù)
XCTestExpectation *expectation = [self expectationWithDescription:@“期待你是好人吧”];
// 調用方法;
[self.vc loadTheData:^(id data) {
// 邏輯判斷
XCTAssertNotNil(data);
[ec fulfill];//給信號,證明回來了
}];
// 判斷查看結果
[self waitForExpectationsWithTimeout:5 handler:^(NSError * _Nullable error) {
NSLog(@"error = %@",error);
// 5秒后 上邊loadData沒回來([ec fulfill]; 沒被執(zhí)行),這里報錯。
// 報錯信息:Asynchronous wait failed: Exceeded timeout of 0.5 seconds, with unfulfilled expectations: "期待你是好人吧".
}];
}
## 3)性能測試;
// 性能只有相對性 -- 1s or 0.5s or 2s
- (void)testPerformanceExample {
[self measureBlock:^{
// 測試性能:
// 總時間, 平均時間
// 散列分布, 數(shù)學統(tǒng)計學…….
// 不做測試考慮范圍
[self.vc openSysCamera];//提供條件 #
//[self.vc openSysCamera];//局部測試
[self startMeasuring]; //標記 這里開始,,,上邊#處不做測試考慮范圍
[self.vc openSysCamera];//局部測試
[self stopMeasuring];
}];
}
- (void)testPerformance{
[self measureMetrics:@[XCTPerformanceMetric_WallClockTime]
automaticallyStartMeasuring:NO forBlock:^{
[self.vc openSysCamera];//提供條件
[self startMeasuring];
[self.vc openSysCamera];//局部測試
[self stopMeasuring];
}];
}