Search code examples
kotlinmockitospring-test

How to correctly use Mockito's verify on a spring @Service test


I have this service (all in kotlin):

@Service
class MyService {

  fun getSomeString(): String = "test"
}

And this integration test class:

@RunWith(SpringRunner::class)
@SpringBootTest
@EmbeddedKafka // used on some kafka tests
class BasicTests {

and method:

@Test
fun `test method count`() {
    // here I have a kafka producer sending a message to a topic that ends up 
    // calling myService.getSomeString via @KafkaListener from other services
    verify(someObjectRelatedToMyService, atLeast(1)).getSome()
}

In the place of someObjectRelatedToMyService I tried to use

@Autowired
lateinit var myService: MyService

But then I got Argument passed to verify() is of type MyService and is not a mock!

But when I use

@Mock
lateinit var myMock: MyService

I get Actually, there were zero interactions with this mock.

And actually, to me it makes sense, since my mock wasn't called, but my real service at the application was.

Is it possible to count method calls from my real object?


Solution

  • You can spy on the real object to count method calls on it like this:

    @Test
    fun `test method count`() {
        Mockito.spy(someObjectRelatedToMyService)
        verify(someObjectRelatedToMyService, atLeast(1)).getSome()
    }
    

    As you can see, the only thing you have to do is to call the spy method which enables tracking interactions with the target object.

    When adding this call before the verify method, you should not get the error anymore that the object is not a mock.