I'm using XCTestExpectations in Xcode 6 (Beta 5) for asynchronous testing. All my asynchronous tests pass individually every time I run them. However, when I try to run my entire suite, some tests do not pass, and the app crashes.
The error I get is says API violation - multiple calls made to -[XCTestExpectation fulfill]
. Indeed, this is not true within a single method; my general format for my tests is shown below:
- (void) someTest {
/* Declare Expectation */
XCTestExpectation *expectation = [self expectationWithDescription:@"My Expectation"];
[MyClass loginOnServerWithEmail:@"example@email.com" andPassword:@"asdfasdf" onSuccess:^void(User *user) {
/* Make some assertions here about the object that was given. */
/* Fulfill the expectation */
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:^(NSError *error) {
/* Error handling here */
}];
}
Again, these tests do pass when run individually, and they are actually making network requests (working exactly as intended), but together, the collection of tests fail to run.
I was able to have a look at this post here, but was unable to get the solution to work for me.
Additionally, I'm running OSX Mavericks and using Xcode 6 (Beta 5).
Here is probably the answer you are looking for :
XCTestExpectation: how to avoid calling the fulfill method after the wait context has ended?
It at least fixed the issue for me.
I don't think using
__weak
or__block
is a good approach. I have written many unit tests usingXCTestExpectation
for awhile and never had this problem until now. I finally found out that real cause of the problem which potentially may cause bugs in my app. The root cause of my problem is thatstartAsynchronousTaskWithDuration
calls the completionHandler multiple time. After I fix it the API violation went away!Although it took me a few hours to fix my unit tests but I came to appreciate the API violation error which will help me avoid future runtime problem in my app.
Try declaring your expectationWithDescription as weak and unwrap the optional "expected" variable.
This avoids deallocation of asyncExpectation variable and calling your expectation on nil.
I think it's likely that you have a retain cycle issue somewhere preventing to release your object which is calling the block in which the expectation is fulfill multiple time.
Otherwise, if it's an expected behavior that your expectation is called multiple time, I've write a little extension allowing to specify an expectation count:
full code (with test :) here: https://gist.github.com/huguesbr/7d110bffd043e4d11f2886693c680b06