iOS中异步回调的单元测试方法

来源:互联网 发布:珠三角物流网络 编辑:程序博客网 时间:2024/05/29 19:41

在XCode6以上版本中,苹果添加了用于异步回调测试的api,因此不用像旧版本那样,发起异步调用后通过循环查询标志位,来检查异步回调函数的调用了。
在新版本中直接使用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失败;反之若成功请求则会在回调函数中打印出返回头,并触发单测成功。

0 0