8

PS: Code will be in Koltin

For example, I have my service class that does something and injects some other service.

class MyService(
   private val someOtherService: OtherService
) {
   fun doSomething() {
       someOtherService.someMethod("foo")
       someOtherService.someMethod("bar")
       someOtherService.someMethod("baz")
   }
}

Here is my test to my MyService class which mocks OtherService:

internal class MyServiceTest {
    @MockkBean(relaxed = true)
    private lateinit var someOtherService: OtherService

    @Test
    fun `my test description`() {
        every { someOtherService.someMethod(any()) } just Runs

        verify(exactly = 1) {
            someOtherService.someMethod(
                    match {
                        it shouldBe "bar"
                        true
                    }
            )
        }
    }

As a result, "bar" parameter will be expected but will be "foo" parameter instead and the test will fail.

Reason: someOtherService.someMethod("foo") will have called before someOtherService.someMethod("bar").

However, I want to verify that every method called exactly once. How I can do that?

Seydazimov Nurbol
  • 1,404
  • 3
  • 10
  • 25

1 Answers1

13

You could just:

verifySequence {
  someOtherService.someMethod("foo")
  someOtherService.someMethod("bar")
  someOtherService.someMethod("baz")
}

It verifies that only the specified sequence of calls were executed for mentioned mocks.

Mockk verification-order

If not, you could capture the parameter using a list and verify the values later.

Mockk capturing

alfcope
  • 2,327
  • 2
  • 13
  • 21