Elye
Elye

Reputation: 60081

How could I test a method is not being called for a non mock object?

I have a test as below, where in the given condition, I want to ensure mainPresenter.presenterFunction() is not called.

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()
    }
}

However it error out stating

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!

The error is on the line verify(mainPresenter, never()).presenterFunction()

It is expected as mainPresenter is not a mock object. How could I test a method that being called for a non mock object?

I see the answer in how to verify a method of a non-mock object is called?, but that is still using Mock and Spy. I hope to find a way without need to mock for a class instance that I already have.

(Note: the above is written in Kotlin)

Upvotes: 3

Views: 2378

Answers (1)

Krzysztof Kozmic
Krzysztof Kozmic

Reputation: 27374

That won't work by definition.

Mocking frameworks can verify only calls to mock objects. They have no way of knowing what has or hasn't happened to objects they do not control. You either need to mock your presenter, replace it with a stub or...

well, I think those are the only two options.

Upvotes: 6

Related Questions