iOS中异步回调的单元测试方法
2016-08-11 14:33
1241 查看
在XCode6以上版本中,苹果添加了用于异步回调测试的api,因此不用像旧版本那样,发起异步调用后通过循环查询标志位,来检查异步回调函数的调用了。
在新版本中直接使用
首先来看一下官方文档中的代码片段:
步骤就是:
在单测开始位置声明需要使用的Expectation对象,在回调中触发
官方文档使用的block方式回调。对于代理方式的回调,同样适用。不过由于回调函数在单测函数外侧,需要把变量声明到类中,这里通过
如果网络不通,那么10s超时后就会导致case失败;反之若成功请求则会在回调函数中打印出返回头,并触发单测成功。
在新版本中直接使用
XCTestExpectation的API即可实现这一功能。
首先来看一下官方文档中的代码片段:
- (void)testDocumentOpening { // 创建一个expectation对象 XCTestExpectation *documentOpenExpectation = [self expectationWithDescription:@"document open"]; NSURL *URL = [[NSBundle bundleForClass:[self class]] URLForResource:@"TestDocument" withExtension:@"mydoc"]; UIDocument *doc = [[UIDocument alloc] initWithFileURL:URL]; [doc openWithCompletionHandler:^(BOOL success) { XCTAssert(success); // assert成功后 便会调用expectation的fulfill方法,来触发下面的handler [documentOpenExpectation fulfill]; }]; // 在case最后使用这一方法,此时单测程序会阻塞到这里;除非达到了超时时间(秒单位)或者是回调函数中调用了fulfill,单测程序才会结束 // 若是超时情况,则认为case失败;若通过expectation的fulfill触发,则case通过 [self waitForExpectationsWithTimeout:1 handler:^(NSError *error) { [doc closeWithCompletionHandler:nil]; }]; }
步骤就是:
在单测开始位置声明需要使用的Expectation对象,在回调中触发
fulfill函数,单测的末尾调用api进行等待。
官方文档使用的block方式回调。对于代理方式的回调,同样适用。不过由于回调函数在单测函数外侧,需要把变量声明到类中,这里通过
NSURLConnection异步GET回调来说明:
#import <XCTest/XCTest.h> @interface HelloWorldXCodeTests : XCTestCase @end @implementation HelloWorldXCodeTests // 回调对应的Expectation对象 XCTestExpectation *networkSuccessExpectation; - (void)setUp { [super setUp]; } - (void)tearDown { [super tearDown]; } - (void)testNetworkOpening { networkSuccessExpectation = [self expectationWithDescription:@"document open"]; // 创建url NSURL *url = [NSURL URLWithString:@"https://api.douban.com/v2/book/1220562"]; // 创建请求 NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; // 连接服务器 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; [connection start]; // 等待回调方法,10秒超时 [self waitForExpectationsWithTimeout:10 handler:^(NSError *error) { NSLog(@"test case over"); }]; } // 异步GET请求回调 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSHTTPURLResponse *res = (NSHTTPURLResponse *)response; NSLog(@"http connection: %@",[res allHeaderFields]); // 触发fulfill方法,跳出单测程序等待状态 [networkSuccessExpectation fulfill]; } @end
如果网络不通,那么10s超时后就会导致case失败;反之若成功请求则会在回调函数中打印出返回头,并触发单测成功。
相关文章推荐
- iOS开发:同步方法中混杂异步方法,导致异步方法还没有回调,同步方法就返回了值,因此返回了nil。解决方法
- iOS 网络开发NSURLConnection——使用block回调方法发送异步请求
- iOS单元测试中测试异步方法
- iOS网络编程异步GET方法请求编程
- ios 坑爹的 APNS 回调方法didReceiveRemoteNotification
- ios 单元测试方法说明
- iOS中异步函数的单元测试
- C# 委托异步回调 基本使用方法
- ios开发中实现回调的方法
- iOS 自定义回调方法(自用)
- c#异步回调方法
- RMI异步回调方法调用
- 如何:使用回调方法实现异步 Web 服务客户端
- IOS开发笔记-NSURLConnection同步请求和异步请求以及get方法,post方法
- IAsyncResult异步执行回调方法的简单使用
- 跨平台python异步回调机制实现和使用方法
- iOS开发之回调delegate的方法时判断delegate是否已经被释放
- 使用异步类管理回调方法
- iOS开发那些事-iOS网络编程异步GET方法请求编程
- iOS开发那些事-iOS网络编程异步GET方法请求编程