6

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.

shaioz
  • 340
  • 3
  • 12
  • See http://stackoverflow.com/questions/12463733/objective-c-unit-testing-dispatch-async-block – Guy Kogus Oct 22 '13 at 16:25
  • Re; your edit to Kazuki's answer (which I see you have changed your mind on). If you like you use that content to add your own answer including the code you used, why it worked etc – Richard Tingle Oct 23 '13 at 12:31
  • Ideally such an answer would go in an answer box however, rather than in the question itself; see the "answer your own question" button – Richard Tingle Oct 23 '13 at 12:32

1 Answers1

2

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.

Community
  • 1
  • 1
Kazuki Sakamoto
  • 13,929
  • 2
  • 34
  • 96