2016-05-05 154 views
0

我有一個測試如下,在給定的條件下,我想確保mainPresenter.presenterFunction()不被調用。我怎麼能測試一個方法不被稱爲非模擬對象?

class MainPresenterTest { 

    val mainPresenter: MainPresenter 
    val mainView: MainView 
    val mainBridge: MainBridge 

    init { 
     mainView = mock(MainView::class.java) 
     webBridge = mock(MainBridge::class.java) 
     mainPresenter = MainPresenter(mainView, mainBridge) 
    } 

    @Before 
    fun setUp() { 
     MockitoAnnotations.initMocks(this) 
    } 

    @Test 
    fun simpleTeset1() { 
     // Given 
     whenMock(mainView.viewFunctionCondition()).thenReturn(true) 

     // When 
     mainPresenter.onTriggger() 

     // Then 
     verify(mainView).viewFunction1() 
     verify(mainPresenter, never()).presenterFunction() 
     verify(mainView, never()).viewFunction2() 
    } 
} 

然而,報錯了,說明

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to verify() is of type MainPresenter and is not a mock! 
Make sure you place the parenthesis correctly! 

的錯誤是可以預期的mainPresenterverify(mainPresenter, never()).presenterFunction()

是不是一個模仿的對象。我怎麼能測試一個被稱爲非模擬對象的方法?

我在how to verify a method of a non-mock object is called?看到答案,但仍然使用Mock和Spy。我希望找到一種方法,無需嘲笑我已經擁有的類實例。

(注意:上面寫的是Kotlin)

+1

正如您鏈接到的答案中所示,間諜旨在解決這個問題 - 讓您驗證非模擬對象實例上的調用。你能解釋爲什麼間諜不能使用嗎? –

+1

你試圖做的事也是一個糟糕的班級設計的標誌。保持內部的私密性,並測試外部行爲。 – nhaarman

回答

4

按照定義,這將不起作用。

模擬框架只能調用模擬對象verify。他們無法知道他們無法控制的物體有或沒有發生過什麼。你或者需要模擬你的主持人,用一個存根取代它或...

好吧,我認爲這是唯一的兩個選擇。

相關問題