Vig
Vig

Reputation: 1522

Kiwi spying on multiple NSNotifications

I am currently spying on postNotification like this

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

The problem is I have multiple notifications with different notification names. How do I access the spy's argument for different notification.

For instance say I have Notification1 and Notification2 the spy argument captures Notification1 but I'm not able to capture the Notification2.

Any ideas of how this can be done?

Upvotes: 0

Views: 112

Answers (2)

Cristik
Cristik

Reputation: 32919

Two approaches come into my mind:

  • stub the sendNotification: method, and build an array with the sent notifications:

    NSMutableArray *sentNotifications = [NSMutableArray array];        
    [[NSNotificationCenter defaultCenter] stub:@selector(postNotification:) withBlock:^id(NSArray *params) {
        NSNotification *notification = params[0];
        [sentNotifications addObject:notification.name];
        return nil;
    }];
    [[sentNotifications shouldEventually] equal:@[@"TestNotification1", @"TestNotification2"]];
    

    if the notifications are not always sent in the same order, you might need another matcher then the equal: one.

  • write a custom matcher that registers as observer and evaluates when asked about the received notifications:

    @interface MyNotificationMatcher : KWMatcher
    - (void)sendNotificationNamed:(NSString*)notificationName;
    - (void)sendNotificationsNamed:(NSArray*)notificationNames;
    @end
    

    which can be used in your tests like this:

    [[[NSNotificationCenter defaultCenter] shouldEventually] sendNotificationsNamed:@[@"TestNotification1", @"TestNotification2"]];
    

As a side note, you don't need to decorate the notifications variable with __block, as you don't need to change the content of that variable (i.e. the pointer value).

Upvotes: 1

Vig
Vig

Reputation: 1522

The solution I ended up using was

__block NSMutableArray *notifications = [[NSMutableArray alloc] init];
        [[NSNotificationCenter defaultCenter] stub:@selector(postNotification:) withBlock:^id(NSArray *params) {
            [notifications addObject:params[0]];
            return nil;
        }];

Upvotes: 0

Related Questions