0

我目前正在postNotification像这样监视

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

问题是我有多个通知名称不同的通知。如何访问间谍的参数以获得不同的通知。

例如说我有 Notification1 和 Notification2 间谍参数捕获 Notification1 但我无法捕获 Notification2。

关于如何做到这一点的任何想法?

4

2 回答 2

1

我想到了两种方法:

  • stub方法,并使用sendNotification:发送的通知构建一个数组:

    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"]];
    

    如果通知并不总是以相同的顺序发送,那么您可能需要另一个匹配器equal:

  • 编写一个自定义匹配器,注册为观察者并在询问收到的通知时进行评估:

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

    可以在您的测试中使用,如下所示:

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

作为旁注,您不需要用 装饰notifications变量__block,因为您不需要更改该变量的内容(即指针值)。

于 2015-05-21T07:38:38.273 回答
0

我最终使用的解决方案是

__block NSMutableArray *notifications = [[NSMutableArray alloc] init];
        [[NSNotificationCenter defaultCenter] stub:@selector(postNotification:) withBlock:^id(NSArray *params) {
            [notifications addObject:params[0]];
            return nil;
        }];
于 2015-05-20T20:16:46.820 回答