ses
ses

Reputation: 13372

scala mockito, verify args - Wanted but not invoked MockitoSugar

 class MockitoTest extends MockitoSugar {

  val serviceMock = mock[Service]

  @Test
  def test(): Unit = {

    import org.mockito.Matchers.{eq => eqTo, _} 

    val serviceMock = mock[Service]

    when( serviceMock.call("one") ).
              thenReturn("123")

    verify( serviceMock, times(1) ).call( eqTo("one") )

    val result1 = serviceMock.call("one")
    ...

I end up having:

Wanted but not invoked: service.call("one"); -> at mockito.MockitoTest.test(MockitoTest.scala:34) Actually, there were zero interactions with this mock.

Do I miss something?

Upvotes: 2

Views: 7016

Answers (2)

ses
ses

Reputation: 13372

Jeff was right about the sequence of the calls. Just simplified:

Basically "verify" should be after call:

  @Test
  def test(): Unit = {

    // GIVEN 
    when( serviceMock. call("one") ).
      thenReturn("123")

    // WHEN
    val result = serviceMock.call("one")

    // THEN
    verify( serviceMock, times(1) ).
      call( eqTo("one") )

    assert(result == "123")
  }

Upvotes: 0

Jeff Bowman
Jeff Bowman

Reputation: 95754

Your test should be structured into three parts:

  1. Create mocks for your collaborators, and use when to describe their intended behavior
  2. Invoke your system under test that interacts with those collaborators
  3. If necessary, verify that some interactions happened.

In your test, you have 2 and 3 reversed, and step 2 invokes the method directly rather than letting your system-under-test invoke it. Your call to verify fails because your call to serviceMock.call("one") hasn't happened yet.

Instead of this:

when( serviceMock.call("one") ).
          thenReturn("123")

verify( serviceMock, times(1) ).call( eqTo("one") )

val result1 = serviceMock.call("one")

You want something like this:

when( serviceMock.call("one") ).
          thenReturn("123")

/** Instead of val result1 = serviceMock.call("one") directly: */
val systemUnderTest = SystemUnderTest(serviceMock)
systemUnderTest.someMethodThatInvokesServiceCall()

verify( serviceMock, times(1) ).call( eqTo("one") )

Upvotes: 4

Related Questions