2015-05-19 82 views
0

我目前刺探postNotification這樣獼猴桃間諜

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

的問題是我有不同的通知名稱的多個通知。我如何訪問間諜的不同通知參數。

例如,說我有Notification1和Notification2間諜參數捕獲通知1,但我無法捕獲通知2。

任何想法如何做到這一點?

+0

我注意到你沒有回答我的答案,做了一些改變,答案不再回應這個問題? – Cristik

回答

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,因爲你不需要改變該變量的內容(即點ter值)。

0

我結束了使用的解決方案是

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