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)帮助开发,节省时间:无需走UI转换流,可以直接到任意界面去测试;
2)检查架构合理性: 如果测试很难写,证明 当前结构 不太优秀。
测试三部曲:
1: 准备数据;
2: 调用方法;
3: 断言结果, 判断查看结果
// 准备数据
int num1 = 100;
int num2 = 200;
// 调用方法;
int sum = [self.Vc getPlusSum: num1 number2: num2 ];
// 断言结果;
XCTAssertEqual( sum, “300”, “错了错了啊”);
书写格式:
方法名必须 以 “test” 开头
文件执行顺序:
- (void) setUp {
}
- (void)tearDown {
}
- (void)testFunc1 {
}
- (void)testFunc2 {
}
// 执行顺序
setUp
testFunc1
tearDown
setUp
testFunc2
tearDown
按测试目的 有哪些种类?
## 1)逻辑测试
- (void)testExample {
// 1000 + 2000 = 3000?
// 准备数据
int num1 = 1000;
int num2 = 2000;
// 调用方法;
int num3 = [self.vc getPlusSum:num1 num2:num2];
// 断言结果;判断查看结果
XCTAssertEqual(num3, 3000, @“草,结果不对了啊!”);
}
## 2) 异步测试
- (void)testAsy {
// 准备数据
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]; 没被执行),这里报错。
// 报错信息:Asynchronous wait failed: Exceeded timeout of 0.5 seconds, with unfulfilled expectations: "期待你是好人吧".
}];
}
## 3)性能测试;
// 性能只有相对性 -- 1s or 0.5s or 2s
- (void)testPerformanceExample {
[self measureBlock:^{
// 测试性能:
// 总时间, 平均时间
// 散列分布, 数学统计学…….
// 不做测试考虑范围
[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];
}];
}