转载自:http://blog.csdn.net/diyagoanyhacker/article/details/8540239
通常单元测试执行顺序执行后进程就退出了,对于异步函数(如:网络访问等)的测试比较麻烦。在iOS开发中可以利用Runloop来阻塞主线程,在回调函数中做断言。
代码片段如下,完整Demo
// // SampleTest.m // SampleTest // // Created by Magic Yang on 5/11/12. // Copyright (c) 2012 Baidu. All rights reserved. // #import "SampleTest.h" @implementation SampleTest { int statusCode; } - (void)setUp { [super setUp]; statusCode = -1; } - (void)tearDown { // Tear-down code here. [super tearDown]; } - (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 { // ... } @end