2015-05-15 37 views
1

所以我需要測試NSNotification是否已發佈。我嘗試了下面的代碼來窺探論證。在獼猴桃中測試NSNotification iOS

[[NSNotificationCenter defaultCenter] stub:@selector(postNotification:)]; 

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

[[theValue(notificationSpy.argument.name) should] equal:theValue(SOME_NOTIFICATION)]; 

但這個問題是因爲它是異步的參數並不總是在測試前捕獲。我無法爲notificationSpy.argument.name添加shouldEventually,因爲它在捕獲前會拋出NSInternalConsistencyException以訪問參數。

我也試過, [[SOME_NOTIFICATION should] bePosted]; 它也失敗了。

回答

3

您可以使用expectFutureValue()如果你希望在未來某個時候將要發送的通知:

[[expectFutureValue(((NSNotification*)notificationSpy.argument).name) shouldEventually] equal:@"MyNotification"]; 

你也不會得到NSInternalConsistencyException例外,獼猴桃似乎好工作與間諜尚未解決,如果包裹在expectFutureValue內。

其他替代將

  • stubsendNotification:方法和「手動」捕捉到發送的通知:

    __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"]; 
    
  • 編寫註冊到通知中心自定義的匹配,並斷言在匹配器:

    [[[NSNotificationCenter defaultCenter] shouldEventually] sendNotification:@"MyNotification"]]; 
    

就我個人而言,我會使用自定義匹配器方法,它更優雅,更靈活。

+0

即使我使用expectFutureValue,我仍然會得到NSInternalConsistencyException,就像您提到的那樣。 – Vig

+0

另外,只是想知道你將如何監視多個通知?即說我已經發布了兩個不同的通知notificationSpy.argument.name只是第一個權利,我將如何窺探第二個? – Vig

+0

嗯......我發佈之前測試了代碼,它對我很有用。你在用什麼SDK? – Cristik

1

我可能缺少一些上下文,因爲您沒有解釋正在測試的代碼。你是否發佈通知?或者你是否試圖斷言IOS框架爲你發佈通知?無論如何,這裏有我與您的方法看問題:

  1. 你需要運行的行動,帖子的通知後,刺探postNotification選擇,並在您斷言窺探參數的值。從您發佈的代碼中,不清楚是否發生了這種情況。

  2. 如果確實調用了postNotification方法,該解決方案應該可以工作。我其實不認爲這是一個異步問題。我經常在defaultCenter上窺探postNotificationName:object:userInfo:成功並且沒有特殊的異步處理代碼。

  3. 爲了檢查獼猴桃中字符串的等同性,不要將它們包裝在值()中。 theValue()用於檢查標量屬性上的相等性。你的說法應該是這樣的:

    [[((NSNotification*)notificationSpy.argument).name should] equal:@"myNotificationName"]; 
    

如果這沒有幫助你的解決方案,請提供您正在測試的方法,並在其整體的測試方法更多的代碼,以及任何其他有用的信息。

+0

非常感謝,我遵循相同的方式,並提到我得到NSInternalConsistencyException因爲參數還沒有被窺探。 – Vig

相關問題