2016-05-17 93 views
0

我正在使用螺栓框架进行异步任务。如何测试continueWithBlock部分中的代码?OCMOCK测试块

BOOL wasFetchedFromCache; 
    [[store fetchFileAsync:manifestURL allowfetchingFromCache:YES fetchedFromCache:&wasFetchedFromCache] 
     continueWithBlock:^id(BFTask *task) { 
      NSData *fileContents = task.result; 
      NSError *localError; 

      // code to test 
      return nil 
     }]; 

回答

0

为了测试异步任务,您应该使用XCTestExpectation,它允许我们创建一个将在未来实现的期望。这意味着返回的未来结果被认为是测试用例中的一个期望,并且测试将等待直到收到声明的结果。请看下面的代码,我写了一个简单的异步测试。

- (void)testFetchFileAsync { 
    XCTestExpectation *expectation = [self expectationWithDescription:@"FetchFileAsync"]; 
    BOOL wasFetchedFromCache; 
    [[store fetchFileAsync:manifestURL allowfetchingFromCache:YES fetchedFromCache:&wasFetchedFromCache] 
    continueWithBlock:^id(BFTask *task) { 
     NSData *data = task.result; 
     NSError *localError; 

     XCTAssertNotNil(data, @"data should not be nil"); 

     [expectation fulfill]; 
     // code to test 
     return nil 
    }]; 

    [self waitForExpectationsWithTimeout:15.0 handler:^(NSError * _Nullable error) { 
     if (error) { 
      NSLog(@"Timeout error"); 
     } 
    }]; 

    XCTAssertTrue(wasFetchedFromCache, @"should be true"); 
}