异步测试,有三种方式(expectationWithDescription,expectationForPredicate和expectationForNotification)
- expectationWithDescription:设置预期描述
- (void)testExpection {
XCTestExpectation *exp = [self expectationWithDescription:@"这里写操作出错的原因描述等"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperationWithBlock:^{
//模拟这个异步操作需要2秒后才能获取结果,比如一个异步网络请求
sleep(2);
//模拟获取的异步操作后,获取结果,判断异步方法的结果是否正确
XCTAssertEqual(@"a", @"a");
//fulfill表示满足期望 该方法用于表示这个异步测试结束了,每一个XCTestExpectation对象都需要对应一个fulfill,否则将会导致测试失败, 如果断言没问题,就调用fulfill宣布测试满足
[exp fulfill];
}];
//设置延迟多少秒后,如果没有满足测试条件就报错
[self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
// 等待3秒,若该测试未结束(未收到 fulfill方法)则测试结果为失败
if (error) {
NSLog(@"Timeout Error: %@", error);
}
}];
}
2、expectationForPredicate......怎么有种谓词正则的感觉呢
- (void)testAsynExampleWithExpectationForPredicate {
XCTAssertNil(self.imageView.image);
self.imageView.image = [UIImage imageNamed:@"icon2"];
//设置一个期望
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"image != nil"];
//若在规定时间内满足期望,则测试成功
[self expectationForPredicate:predicate
evaluatedWithObject:self.imageView
handler:nil];
// 超时后执行
[self waitForExpectationsWithTimeout:10.0 handler:^(NSError * _Nullable error) {
}];
}
3、expectationForNotification: 该方法监听一个通知,如果在规定时间内正确收到通知则测试通过
- (void)testAsynExampleWithExpectationForNotification {
//监听通知,在规定时间内受到通知,则测试通过
[self expectationForNotification:@"监听通知的名称测试" object:nil handler:^BOOL(NSNotification * _Nonnull notification) {
NSLog(@"请求成功");
//做后续处理
return YES;
}];
//下面2个地址可以查看测试通过与不通过的区别
//测试通过
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com/"];
//测试失败
// NSURL *url = [NSURL URLWithString:@"www.baidu.com/"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data && !error && response) {
//发送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"监听通知的名称测试" object:nil];
}
}];
[task resume];
//设置延迟多少秒后,如果没有满足测试条件就报错
[self waitForExpectationsWithTimeout:10.0 handler:^(NSError * _Nullable error) {
[task cancel];
}];
}
截取AFNetworking获取背景图片的方法
- (void)testThatBackgroundImageChanges {
XCTAssertNil([self.button backgroundImageForState:UIControlStateNormal]);
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(UIButton * _Nonnull button, NSDictionary<NSString *,id> * _Nullable bindings) {
return [button backgroundImageForState:UIControlStateNormal] != nil;
}];
[self expectationForPredicate:predicate
evaluatedWithObject:self.button
handler:nil];
[self waitForExpectationsWithTimeout:20 handler:nil];
}