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.
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
stub
the sendNotification:
method and "manually" capture the sent notification:
__block NSString *notifName = nil;
[[NSNotificationCenter defaultCenter] stub:@selector(postNotification:) withBlock:^id(NSArray *params) {
NSNotification *notification = params[0];
notifName = notification.name;
return nil;
}];
[[notifName shouldEventually] equal:@"TestNotification"];
write a custom matcher that registers to the notification center and assert on that matcher:
[[[NSNotificationCenter defaultCenter] shouldEventually] sendNotification:@"MyNotification"]];
Personally, I'd go with the custom matcher approach, it's more elegant and more flexible.