objective-cunit-testingnsnotificationskiwi

Testing NSNotification in Kiwi iOS


So I need to test whether a NSNotification is posted. I tried the following code to spy on the argument.

[[NSNotificationCenter defaultCenter] stub:@selector(postNotification:)];

__block KWCaptureSpy *notificationSpy = [[NSNotificationCenter 
defaultCenter] captureArgument:@selector(postNotification:) atIndex:0];

[[theValue(notificationSpy.argument.name) should] equal:theValue(SOME_NOTIFICATION)];

but the problem with this is the since it's asynchronous the argument is not always captured before testing. I can't add shouldEventually for notificationSpy.argument.name either as it throws NSInternalConsistencyException for accessing the argument before capturing.

I also tried, [[SOME_NOTIFICATION should] bePosted]; and it failed as well.


Solution

  • You can use expectFutureValue() if you expect the notification to be sent sometime in the future:

    [[expectFutureValue(((NSNotification*)notificationSpy.argument).name) shouldEventually] equal:@"MyNotification"];
    

    You also won't get the NSInternalConsistencyException exception, as Kiwi seems to work fine with spies not yet resolved, if wrapped inside a expectFutureValue.

    Other alternatives would be to

    Personally, I'd go with the custom matcher approach, it's more elegant and more flexible.