Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using [NSOperationQueue mainQueue] in XCTests

I'm testing a part of my code using using XCTest that also adds NSOperations on the main queue. It looks like this:

[NSOperationQueue mainQueue] addOperationAsBlock:^{ // some code happens here }];

The code runs when running the app on a device or in the simulator but doesn't run at all when running the unit test (I can't get to the debug point on the first line of the block).

calling:

[NSOperationQueue mainQueue] waitUntilAllOperationsAreFinished];

doesn't help as well.

Any suggestions? I think i'm missing some code to initialise the queue.

* EDIT *

Thanks for your answers, I added my resulting code for completeness:

// add as many operations as you'd like to the mainQueue here
__block BOOL continueCondition = YES;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    // this should be the last operation
    continueCondition = NO;
}];
while (continueCondition)  {
    [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} // continue your test here

This works because the mainQueue is guaranteed to be non-concurrent so the last operation that's added will be the last one executed - this way you don't even have to change your code to stop the test loop.

like image 215
shaioz Avatar asked Oct 22 '13 16:10

shaioz


1 Answers

Same as IOS -NSRunLoop in XCTest: How Do I Get A Run Loop to Work in A Unit Test?

Also, aquarius / XCTestCase+MNAsynchronousTestCase.h is helpful for it.

like image 144
Kazuki Sakamoto Avatar answered Nov 12 '22 07:11

Kazuki Sakamoto