【问题标题】:Kiwi spying on multiple NSNotificationsKiwi 监视多个 NSNotifications
【发布时间】:2015-05-19 17:10:44
【问题描述】:

我目前正在像这样监视postNotification

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

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

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

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

【问题讨论】:

  • 我注意到您不接受我的回答,是否发生了一些变化并且答案不再响应问题?

标签: objective-c nsnotification kiwi


【解决方案1】:

我想到了两种方法:

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

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

附带说明,您无需使用__block 修饰notifications 变量,因为您无需更改该变量的内容(即指针值)。

【讨论】:

    【解决方案2】:

    我最终使用的解决方案是

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

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多