Xcode 6异步测试

在进行http通信时常常使用异步,xcode6新增加了异步单元测试的功能。
之前我们在进行异步测试时,只能阻塞主线程等待通信结束。如下:
- (void)testAsyncTheOldWay
    {
        NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:5.0];
        __block BOOL responseHasArrived = NO;
     
        [self.pageLoader requestUrl:@"http://bignerdranch.com"
                  completionHandler:^(NSString *page) {
                   
            NSLog(@"The web page is %ld bytes long.", page.length);
            responseHasArrived = YES;
            XCTAssert(page.length > 0);
        }];
     
        while (responseHasArrived == NO && ([timeoutDate timeIntervalSinceNow] > 0)) {
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, YES);
        }
     
        if (responseHasArrived == NO) {
            XCTFail(@"Test timed out");
        }
    }


其中轮询判断状态及timeout时间。

现在的xcode6,如下进行异步测试:

(void)testWebPageDownload
    {
        XCTestExpectation *expectation =
            [self expectationWithDescription:@"High Expectations"];
        [self.pageLoader requestUrl:@"http://bignerdranch.com"
                  completionHandler:^(NSString *page) {
                   
            NSLog(@"The web page is %ld bytes long.", page.length);
            XCTAssert(page.length > 0);
            [expectation fulfill];
        }];
     
        [self waitForExpectationsWithTimeout:5.0 handler:^(NSError *error) {
            if (error) {
                NSLog(@"Timeout Error: %@", error);
            }
        }];
    }


在Xcode 6里,苹果以XCTestExpection类的方式向XCTest框架里添加了测试期望(test expection)。当我们实例化一个测试期望(XCTestExpectation)的时候,测试框架就会预计它在之后的某一时刻被实现。最终的程序完成代码块中的测试代码会调用XCTestExpection类中的fulfill方法来实现期望。这一方法替代了我们之前例子里面使用responseHasArrived作为Flag的方式,这时我们让测试框架等待(有时限)测试期望通过XCTestCase的waitForExpectationsWithTimeout:handler:方法实现。如果完成处理的代码在指定时限里执行并调用了fulfill方法,那么就说明所有的测试期望在此期间都已经被实现。否则,这个测试就悲剧了,它会默默的存在程序中而不会被实现哪怕一次……

猜你喜欢

转载自xushans.iteye.com/blog/2188203
今日推荐