单元测试分为3种:
- 逻辑测试:测试逻辑方法
- 异步测试:测试耗时方法(用来测试包含多线程的方法)
- 性能测试:测试某一方法运行所消耗的时间
异步加载个人数据方法的单元测试.png+ (void)loadPersonAsync:(void(^)(Person *person))completion; //异步加载个人数据
Person.m文件:
/** 异步加载个人记录 */
+ (void)loadPersonAsync:(void (^)(Person *))completion {
// 异步 子线程执行
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 模拟网络延迟 2s
[NSThread sleepForTimeInterval:2.0];
Person *person = [Person personWithDict:@{@"name":@"zhang", @"age":@25}];
// 回到主线程
dispatch_async(dispatch_get_main_queue(), ^{
if (completion != nil) {
completion(person);
}
});
});
}
然后,切换到PersonTests.m,新建一个 - (void)testLoadPersonAsync{} 异步测试方法,然后Command+S保存,左边会出现菱形白色调试按钮。
测试中,要用到系统提供的XCTestExpectation
这个类,以及- (void)waitForExpectationsWithTimeout:(NSTimeInterval)timeout handler:(nullable XCWaitCompletionHandler)handler
这个方法来测试,测试代码如下所示:
调试的PersonTests.m文件:
// 测试异步加载person
- (void)testLoadPersonAsync {
XCTestExpectation *expectation = [self expectationWithDescription:@"异步加载 Person"];
[Person loadPersonAsync:^(Person *person) {
// NSLog(@"%@",person);
XCTAssertNotNil(person.name, @"名字不能为空");
XCTAssert(person.age > 0, @"年龄不正确");
// 标注预期达成
[expectation fulfill];
}];
// 等待 5s 期望预期达成
[self waitForExpectationsWithTimeout:5 handler:nil];
}
AFNetworking的单元测试.png