2016-05-17 118 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"); 
}