lundi 14 octobre 2019

How to test through io.mockk a method that was called several times with different parameters?

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?

Aucun commentaire:

Enregistrer un commentaire