3

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)

Community
  • 1
  • 1
Elye
  • 53,639
  • 54
  • 212
  • 474
  • 1
    As demonstrated in the answer you linked to, spy is designed to solve exactly this problem - letting you verify calls on a non-mock object instance. Can you explain why spy can't be used? – Mike Buhot May 05 '16 at 11:27
  • 1
    The thing you're trying to do is also a sign of bad class design. Keep your internals private, and test external behavior. – nhaarman May 05 '16 at 13:06

1 Answers1

6

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.

Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115