I am testing a method that runs in the background and executes a block of code when it ends. I use expectations to handle asynchronous test execution. I wrote a simple test that shows the behavior:
- (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");
}
}];
}
The string XCTFail(@"fail test");should be unsuccessful for this test, but the test passes.
I also noticed that this only happens when the code executed on the callback takes some time (in my case, I checked some files on the file system). This is why the string is usleep(50);needed to reproduce the case.
source
share