Is there a way to verify that some method has been called with specific arguments?
Given this class:
class Log {
fun event(name: String): Boolean = true
}
With Mockito (using the wrapper mockito-kotlin) I can verify that the method was called with some specific argument:
@Test
fun verifyMockito() {
val log = mock<Log>()
whenever(log.event(logName)).thenReturn(false)
log.event(logName)
verify(log, times(1)).event(com.nhaarman.mockito_kotlin.check {
assert(logName == it)
})
}
But using mockk I don't know how to do it without mocking at the same time. Actually, it's not verifying that that method has been called:
@Test
fun verifyMockk() {
val log = mockk<Log>()
//even if I remove this line the test passes, because it is not verifying.
log.event(logName)
//mocking
every { log.event(logName) } returns false
val slot = slot<String>()
//verification but also forcing me to mock again
every { log.event(name = capture(slot))
} answers {
assert(slot.captured == logName)
//have to return the type (again?)
true
}
}
Maybe I'm missing something. But I was not able to find a way of doing this on the docs. How should I address this use case as client of this library?
It should be very easy:
verify {
log.event(logName)
}
My example was not good 馃槄. Imagine you don't have access to logName. How would you do it then? That's the real problem that I'm able to tackle with mockito, but using your library I'm a bit confused. This is how I ended up doing it. Not sure if it is the proper way although.
@Test
fun verifyMockk() {
val log = mockk<Log>()
//logName instance is not accesible from this scope (indirection layers hide this as an internal detail)
log.event(logName)
val slot = slot<String>()
every { log.event(name = capture(slot)) } answers { true }
io.mockk.verify(exactly = 1) { log.event(any()) }
assert(slot.captured == "logName")
}
You can capture in verify, or use assert matcher. Dont remeber right what exact name it has
I see. Much better 馃憤 Thanks!
@Test
fun verifyMockk() {
val log = mockk<Log>()
log.event(logName)
val slot = slot<String>()
verify(exactly = 1) { log.event(name = capture(slot)) }
assert(slot.captured == logName)
}
Since v1.9.+ you can also do something like this:
@Test
fun verifyMockk() {
val log = mockk<Log> {
every { event(any()) } just Runs
}
log.event(logName)
verify(exactly = 1) { log.event(
withArg {
assertThat(it).isEqualTo(logName)
})
}
}
Most helpful comment
Since v1.9.+ you can also do something like this: