Debug MockK “Verification Failed” Errors When You’re Sure the Call Should Match

Almost everyone who’s written unit tests using Kotlin’s mocking library MockK has seen a frustrating verification failed error message:

Verification failed: call 1 of 1: … Only one matching call to {functionName} happened, but arguments are not matching.

This happens when a verify block expects a function to be called with specific arguments, but the actual arguments passed during the test don’t exactly match. Normally, you’d compare the expected and actual values in the error message and figure out what’s wrong.

But what if they look identical?

This usually means there are subtle differences between the arguments that aren’t shown in MockK’s default error logs. This can be due to differences such as "null" vs null, number precision differences, or unexpected object references. In my experience, this problem most often shows up when the argument is a complex object. Here’s how to debug this more effectively.

1. Capture the actual argument using a slot.

To inspect the actual object passed into the function, use a slot. This is a MockK utility that stores the argument passed to a mocked method so you can inspect it later.

Let’s say your function signature is:

fun myFunction(arg1: String, arg2: MyCustomObject)

And you’re trying to verify this call, but arg2 isn’t matching. You can capture it like this:

val capturedArg2 = slot<MyCustomObject>()

verify {
  myFunction("thisIsWhatIExpect", capture(capturedArg2))
}

2. Serialize both arguments to JSON.

After capturing the argument, convert both the expected and actual objects to JSON. This lets you view them in a standardized format and more easily spot subtle differences that might not appear in the Kotlin object representation.

Here’s how to do it using Jackson:

val objectMapper = jacksonObjectMapper()

val expectedJson = objectMapper.writeValueAsString(expectedRequest)
val actualJson = objectMapper.writeValueAsString(capturedArg2.captured)

3.Print, and compare the results.

Now, just print both values to the console:

println("EXPECTED JSON: $expectedJson")
println("ACTUAL JSON  : $actualJson")

From here, you can compare side by side or paste them into a JSON diff checker to find mismatches. For example, one of my tests failed because the actual output had a field set to a string "null" instead of the expected value of null. Then, I was ready to debug the problem.

While this won’t fix your bug on its own, I hope this trick can help save you some time from staring at that MockK’s error output and wondering why the verification is failing when everything looks right.

 
Conversation

Join the conversation

Your email address will not be published. Required fields are marked *