2013-03-07 39 views
3

如何測試的addObserver和removeObserver調用上nsnotificationcenter,使用ocmock在我的基地模擬類

- (void)tearDown 
{ 
    _mockApplication = nil; 
    self.observerMock = nil; 
    self.notificationCenterMock = nil; 
} 

其中notificaitonCenterMock只是一個ID;

在我的測試

然後我做這樣的事情:

self.notificationCenterMock = [OCMockObject partialMockForObject:[NSNotificationCenter defaultCenter]]; 
[(NSNotificationCenter *) [self.notificationCenterMock expect] 
     removeObserver:self.component 
        name:UIApplicationDidBecomeActiveNotification 
       object:nil]; 

現在..如果我運行此代碼我的單元測試會意外失敗(即只370 60將在一個運行,70或65運行下一個)。我的幾個單元測試將失敗,並出現以下錯誤:

OCPartialMockObject[NSNotificationCenter]: expected method was not invoked: removeObserver:  
<VPBCAdComponent-0x17d43e0-384381847.515513: 0x17d43e0> name:@"UIApplicationDidBecomeActiveNotification" object:nil 
Unknown.m:0: error: -[VPBCAdComponentTests testCleanUpAfterDisplayingClickthrough_adBrowser_delegateCallback] :  
OCPartialMockObject[NSNotificationCenter]: expected method was not invoked: removeObserver: 
<VPBCAdComponent-0x17d43e0-384381847.515513: 0x17d43e0> name:@"UIApplicationDidBecomeActiveNotification" object:nil 

測試將被終止。我可以清楚地看到,部分嘲笑通知中心會導致運行測試套件時出現問題。

問題是,我該怎麼辦?這將會是非常好的,以確保重要的事情,如觀察員設置,並且迴歸證明..

+0

或者更具體。我怎樣才能刪除在拆解模擬?似乎將它設置爲零是不夠的。 – Infrid 2013-03-07 20:48:52

+0

你在哪裏調用removeObserver? – psobko 2014-01-30 17:12:57

回答

0

如果你能避免在這種情況下,部分模擬,做到這一點。如果你只想測試觀察者被添加和刪除,你應該能夠使用標準的模擬或好的模擬。

如果你可以隔離短短測試,將驗證觀察員添加和刪除,那麼它不應該有這樣的連鎖反應?

id mockCenter = [OCMockObject mockForClass:[NSNotificationCenter class]]; 
[[mockCenter expect] addObserver:observer options:UIApplicationDidBecomeActiveNotification context:nil]; 

// method on the Subject Under Test 

[mockCenter verify]; 
0

我個人在這種情況下使用本地模擬。較小的模擬範圍確保較少干擾應用程序的其他部分。更重要的是NSUserDefaults或其他共享對象。我使用的測試模式是相同的。

- (void)testRegisterNofificaitonTest { 
    id ncMock = OCMClassMock([NSNotificationCenter class]); 
    OCMStub([ncMock defaultCenter]).andReturn(ncMock); 

    UIViewController *sut = [UIViewController new]; 
    [[ncMock expect] addObserver:sut selector:@selector(doSomething:) name:@"NotificationName" object:nil]; 

    [sut viewDidLoad]; //assuming viewDidLoad calls [[NSNotificationCenter defaultCenter] addObserver: ... 

    [ncMock verify]; 
    [ncMock stopMocking]; 
} 
相關問題