参考资料
概念
单元测试可以分为:
(1)逻辑测试
(2)性能测试
(3)异步测试
(4)UI测试
逻辑错误,通过断言XCTAssertEqual
TDD,测试驱动开发
shift+Command+0(开发者文档)
调用顺序:
+(void)setUp;
-(void)setUp;//把杯子里面的水倒干净,重新进行测试。
-(void)testExample;
-(void)tearDown;
-(void)setUp;
-(void)testPerformanceExample;
-(void)tearDown;
测试的基本结构
1.Given (创建测试添加。数据、初始化的对象、值。OCMock(用来创建测试条件))
2.When (测试方法的参数里面。)
3.Then (断言,是否符合预期。)
eg:
//1.Given
XCTestExpectation *expectation = [self expectationWithDescription:@"Asyn Test is failed"];
//2.When
ViewController *vc = [ViewController new];
[vc sendAsynRequest:^{
//3.Then
[expectation fulfill];//指定时间内没有执行这个方法,异常对象就会抛出
}];
[self waitForExpectationsWithTimeout:2 handler:^(NSError * _Nullable error) {
NSLog(@"---%@",error.localizedDescription);
}];
从哪里开始测试?
测试方法
1.盒子方法。白盒测试,黑盒测试,灰盒测试。
demo
ViewController.h
///逻辑测试
- (NSInteger)addWithNum1:(NSInteger)num1 num2:(NSInteger)num2;
///性能测试
- (void)loadDatas;
///异步测试
- (void)sendAsynRequest:(void(^)(id))block;
ViewController.m
///逻辑测试
- (NSInteger)addWithNum1:(NSInteger)num1 num2:(NSInteger)num2{
return num1+num2;
}
///性能测试
- (void)loadDatas{
for (NSInteger i=0; i<200; i++) {
NSLog(@"性能测试。。。");
}
}
///异步测试
- (void)sendAsynRequest:(void(^)(id))block{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[NSThread sleepForTimeInterval:3];
dispatch_async(dispatch_get_main_queue(), ^{
if (block) {
block(@(random()));
}
});
});
}
ViewControllerTests.m
///逻辑测试
- (void)testLogic{
//1.Given
NSInteger a = 1;
NSInteger b = 2;
//2.When
ViewController *vc = [ViewController new];
NSInteger add = [vc addWithNum1:a num2:b];
//3.Then
XCTAssertEqual(add, 3);
}
///异步测试
- (void)testAsync{
//1.Given
XCTestExpectation *expectation = [self expectationWithDescription:@"Asyn Test is failed"];
//2.When
ViewController *vc = [ViewController new];
[vc sendAsynRequest:^(id obj){
//3.Then
XCTAssertNotNil(obj);
[expectation fulfill];//指定时间内没有执行这个方法,异常对象就会抛出
}];
[self waitForExpectationsWithTimeout:4 handler:^(NSError * _Nullable error) {
NSLog(@"---%@",error.localizedDescription);
}];
}
- (void)testPerformanceExample {
// This is an example of a performance test case.
//性能测试
[self measureMetrics:@[XCTPerformanceMetric_WallClockTime] automaticallyStartMeasuring:NO forBlock:^{
ViewController *vc = [ViewController new];
[self startMeasuring];
[vc loadDatas];
[self stopMeasuring];
}];
// [self measureBlock:^{
// // Put the code you want to measure the time of here.
// ViewController *vc = [ViewController new];
// [vc loadDatas];
// }];
}