2016-11-29 119 views
0

我正在使用Mockito做JUnit測試,並且發現了一個斷言問題。我創建一個模擬對象,然後使用模擬對象創建一個演示者對象。斷言Mockito嘲笑的對象被設置爲空

@Mock 
Object mFooBar; 

private FooPresenter mFooPresenter; 

@Before 
public void setUp() throws Exception { 
    MockitoAnnotations.initMocks(this); 

    mFooPresenter = new FooPresenter(mFooBar); 

} 

在我的演示者的onDestroy()方法中,我將對象清空。

public FooPresenter(Object fooBar) { 
    mFooBar = fooBar; 
} 

@Override 
public void onDestroy() { 
    mFooBar = null; 
} 

然後,當我嘗試在我的FooPresenterTest中爲mFooBar聲明NULL時,它失敗,因爲它不爲空。

@Test 
public void testThatObjectsAreNullifiedInOnDestroy() throws Exception { 
    fooPresenter.onDestroy(); 

    assertNull(mFooBar); 
} 

這未按

Expected :<null> 
Actual :mFooBar 

我的問題,然後是,如何在我的測試類來處理的嘲笑對象的引用相比,我實例化運行測試的對象?爲什麼assertNull在應該被設置爲null時失敗?

+0

嘿@ kerseyd27,我假設你的'FooPresenter'中的'mFooBar'字段是私人的,是否有任何財產暴露它? – abest

+0

嘿@abest是的它是私人的,並沒有暴露的屬性。 – kerseyd27

回答

1

@ kerseyd27,

從測試的名字testThatObjectsAreNullifiedInOnDestroy看來,你正在尋找驗證注入mFooBar對象是由您的主持人釋放時主持人被破壞。

首先,直接回答你的問題:

如何在我的測試類來處理的嘲笑對象的引用相比,我實例化運行測試的對象?

我會讓這些問題的答案(link 1link 2)不言自明,但解釋它是如何涉及到您的問題。模擬對象在Test類中實例化,並通過值傳遞給FooPresenterFooPresenter.mFooBar單獨參考(屬於主持人),指向嘲笑的對象。在調用onDestroy方法之前,TestClass.mFooBarfooPresenter.mFooBar引用同一個對象(模擬對象),但它們是對該對象的兩個不同的引用。

爲什麼assertNull會在應該設置爲null時失敗?

您聲稱Test.mFooBar(屬於Test類)爲null。 Test.mFooBar是在測試設置中創建的,但此變量從不設置爲null。另一方面,fooPresenter.mFooBar變量顯式地設置爲空。同樣,雖然這些變量指向相同的對象,但引用本身並不相同。

如果您希望確保fooPresetner.mFooBar爲空,那麼可以使其成爲本地包或使用屬性公開它。這樣做僅僅是爲了測試目的,通常是不被接受的。

如果你正在尋找,以確保某些動作在構造函數中mFooBar對象執行,你可以寫一個測試類似如下:

public class TestClass { 

    interface FooBar { 
     void releaseSomething(); 
    } 

    @Rule 
    public MockitoRule r = MockitoJUnit.rule(); 

    @Mock 
    FooBar mFooBar; 

    @Test 
    public void testThatObjectsAreNullifiedInOnDestroy() { 
     new FooPresenter(mFooBar).onDestroy(); 
     verify(mFooBar).releaseSomething(); 
    } 

    class FooPresenter { 
     private FooBar mFooBar; 

     public FooPresenter(FooBar fooBar) {this.mFooBar = fooBar;} 

     @Override 
     void onDestroy() { 
      mFooBar.releaseSomething(); 
      mFooBar = null; 
     } 
    } 
} 

好運&快樂測試!

+0

這確實回答了我的具體問題。有了這些信息,我爲我的案例所做的工作就是在onDestroy被調用後,在我的課程中驗證所有模擬對象的NoMoreInterations;這是因爲我同意爲了測試目的而對此進行編碼改變是不被接受的。謝謝 – kerseyd27