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

Szymon Jeziorski

02/26/2022, 1:01 PM
Hello everyone. I'm trying to make use of
verify
- verifying method call with the argument being an object equal to another object comparing field by field but ignoring one or more fields. So far the only reasonable solution I came up with was creating a
matcher
using AssertJ's
usingRecursiveComparison()
and wrapping it to `runCatching`:
Copy code
inline fun <reified T : Any> MockKVerificationScope.matcherFor(expected: T, vararg ignoredFields: String) = match<T> {
    runCatching {
        assertThat(it).usingRecursiveComparison().ignoringFields(*ignoredFields).isEqualTo(expected)
    }.isSuccess
}
example usage:
Copy code
verify {
    userRepository.save(matcherFor(expectedUser, "id"))
}
I found the above to be elegant enough from the calling side but was wondering if there would be any more straightforward way to achieve the same with less overhead at the same time. Thanks in advance for any suggestions!
m

Mattia Tommasone

02/26/2022, 4:07 PM
i think the most explicit way to achieve the same comparison would be to use a slot to capture the parameter being passed, and then explicitly asserting that the fields in your slot’s captured value have the values that you expect. something like this:
Copy code
val slot = slot<YourType>()
verify {
    userRepository.save(capture(slot))
}
val captured = slot.captured
assertEquals(captured.someProperty, "expectedValue")
...
s

Szymon Jeziorski

02/26/2022, 4:17 PM
Thanks, but the thing is I wanted to avoid asserting each field individually for conciseness and also wanted to make the approach universal. Also, in my scenario, I would rather use
matcher
rather than
slot
as I want to check if the method was called with some particular argument but I'm not assuming it was the first/only call to this method
2 Views