0

我正在将螺栓框架用于异步任务。如何测试 continueWithBlock 部分中的代码?

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

            // code to test
            return nil
        }];
4

1 回答 1

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");
}
于 2016-05-17T16:58:06.873 回答