Skip to main content

OCUnit with asynchronous methods

Alternate A

-(void)testAsync
{
   // create the semaphore and lock it once before we start
   // the async operation
   NSConditionLock * conditionLock = [NSConditionLock new];
   self.theLock = conditionLock;  

   // start the async operation
   ...

   // now lock the semaphore - which will block this thread until
   // [self.theLock unlockWithCondition:1] gets invoked
   [self.theLock lockWhenCondition:1];

   // make sure the async callback did in fact happen by
   // checking whether it modified a variable
   STAssertTrue (self.testState != 0, @"delegate did not get called");
}

-(void)myDelegate
{
   [self.theLock unlockWithCondition:1];
}

Stackoverflow
Apple Developer NSConditionLock Class Reference

Alternate B


dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

^{
...
dispatch_semaphore_signal(semaphore);
}

while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
}

MobileCraft

Comments