バックグラウンドで実行され、終了時にコード ブロックを実行するメソッドをテストしています。テストの非同期実行を処理するために期待を使用しています。動作を示す簡単なテストを作成しました。
- (void) backgroundMethodWithCallback: (void(^)(void)) callback {
dispatch_queue_t backgroundQueue;
backgroundQueue = dispatch_queue_create("background.queue", NULL);
dispatch_async(backgroundQueue, ^(void) {
callback();
});
}
- (void) testMethodWithCallback {
XCTestExpectation *expectation = [self expectationWithDescription:@"Add collection bundle"];
[self backgroundMethodWithCallback:^{
[expectation fulfill];
usleep(50);
XCTFail(@"fail test");
}];
[self waitForExpectationsWithTimeout: 2 handler:^(NSError *error) {
if (error != nil) {
XCTFail(@"timeout");
}
}];
}
このXCTFail(@"fail test");
テストでは回線は失敗するはずですが、テストは成功しています。
また、これはコールバックで実行されたコードに時間がかかる場合にのみ発生することにも気付きました (私の場合、ファイル システム上のいくつかのファイルをチェックしていました)。これがusleep(50);
、ケースを再現するために線が必要な理由です。