变更记录
方案名称
测试 - 异步函数的单元测试
关键字
测试 \ 单元测试 \ 异步函数 \ delegate \ 代理 \ block
需求场景
- 需要对 Block 异步回调进行结果测试时
- 需要对 Delegate 异步回调进行结果测试时
参考链接
- CSDN - iOS中异步函数的单元测试
- Stack Overflow - How do I unit test HTTP request and response using NSURLSession in iOS 7.1?
详细内容
1. Block 回调类异步测试
使用 XCTestExpectation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| - (void)testDataTask { XCTestExpectation *expectation = [self expectationWithDescription:@"asynchronous request"];
NSURL *url = [NSURL URLWithString:@"http://www.apple.com"]; NSURLSessionTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { XCTAssertNil(error, @"dataTaskWithURL error %@", error);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode]; XCTAssertEqual(statusCode, 200, @"status code was not 200; was %d", statusCode); }
XCTAssert(data, @"data nil");
// do additional tests on the contents of the `data` object here, if you want
// when all done, Fulfill the expectation
[expectation fulfill]; }]; [task resume];
[self waitForExpectationsWithTimeout:10.0 handler:nil]; }
|
使用 dispatch_semaphore_
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| - (void)testDataTask { dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURL *url = [NSURL URLWithString:@"http://www.apple.com"]; NSURLSessionTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { XCTAssertNil(error, @"dataTaskWithURL error %@", error);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode]; XCTAssertEqual(statusCode, 200, @"status code was not 200; was %d", statusCode); }
XCTAssert(data, @"data nil");
// do additional tests on the contents of the `data` object here, if you want
// when all done, signal the semaphore
dispatch_semaphore_signal(semaphore); }]; [task resume];
long rc = dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 60.0 * NSEC_PER_SEC)); XCTAssertEqual(rc, 0, @"network request timed out"); }
|
2. Delegate 回调类异步测试
使用 CFRunLoop_
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| - (void)testExample { NetworkHelper *helper = [[NetworkHelper alloc] initWithDelegate:self]; [helper getStatusCodeForSite:@"http://www.baidu.com"]; NSLog(@"------------------ Waiting ------------------"); CFRunLoopRun(); STAssertTrue(statusCode == 200, @"Can not access this site"); NSLog(@"------------------ Finished ------------------"); }
- (void)succeedGotStatusCode:(int)code { statusCode = code; CFRunLoopRef runLoopRef = CFRunLoopGetCurrent(); CFRunLoopStop(runLoopRef); }
- (void)failedGotStatusCodeWithError:(NSError *)error { // ... }
|
效果图
(无)
备注
(无)