https://kotlinlang.org logo
#mockk
Title
# mockk
j

Jakub Gwóźdź

02/06/2023, 12:18 PM
Hi folks. A question about best practice for verifying call arguments in mockk (we’re using strikt here, but the question is general). Imagine such setup:
Copy code
interface Dependency {
        fun bar(i: Int): Int
    }

    class Service(val injected: Dependency) {
        fun foo(i: Int) = injected.bar(i * 2) / 3
    }

    private val mock = mockk<Dependency> { every { bar(any()) } returns 42 }
    private val service = Service(mock)
Would you rather do `capture`:
Copy code
@Test
    fun testUsingCapture() {
        val arg = slot<Int>()
        val result = service.foo(100)
        verify { mock.bar(capture(arg)) }
        expect {
            that(arg).captured isEqualTo 200
            that(result) isEqualTo 14
        }
    }
or `withArg`:
Copy code
@Test
    fun testUsingWithArg() {
        val result = service.foo(100)
        verify {
            mock.bar(
                withArg {
                    expectThat(it) isEqualTo 200
                }
            )
        }
        expectThat(result) isEqualTo 14
    }
?
m

Mattia Tommasone

02/06/2023, 4:20 PM
i guess it’s a matter of personal taste: i find the version with
capture
easier to read because it clearly separates the call recording from the assertions
26 Views