Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test async method in block using OCMock

I can't seem to figure out how to test this method:

- (void)writer:(id)writer didFailWithError:(NSError *)error;
{    
 [self.alertView dismissWithClickedButtonIndex:0 animated:YES];

  void (^alertViewBlock)(int) = ^(int buttonIndex)
  {
    if (buttonIndex == 1)
    {
        [self performSelectorOnMainThread:@selector(savePostponeReasonsAsynchronously) withObject:nil waitUntilDone:NO];
    }
    else
    {
        NSLog(@"dismissed");

        self.savePostponeReasonsQueue = nil;
    }
  };

 [self showPostponeReasonFailedAlert:alertViewBlock];
}

Specifically how do I test that the selector savePostponeReasonsAsynchronously was called?

thanks

like image 715
jimijon Avatar asked Apr 30 '26 00:04

jimijon


1 Answers

One way to test asynchronous method calls is to wait for them to complete:

__block BOOL isRunning = YES;
[[[myPartialMock expect] andDo:^(NSInvocation *invocation){ isRunning = NO; }] savePostponeReasonsAsynchronously];
myPartialMock writer:nil didFailWithError:nil; 

NSDate *timeout = [NSDate dateWithTimeIntervalSinceNow:10];
do {
  [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                           beforeDate:timeout];
} while (isRunning);

STAssertFalse(isRunning, @"Test timed out.");
[myPartialMock verify];

This is a technique I learned by looking at Rob Napier's test code for RNCryptor, which also has some nice tricks using semaphores.

like image 58
Ben Flynn Avatar answered May 03 '26 09:05

Ben Flynn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!