Search code examples
kotlinjunitmockito

Kotlin - Mockito when using object equality instead of checking reference


Lets assume we have following method I want to write unit test for using Mockito

fun myMethod(
        param1: String,
        param2: Int
    ): List<ResultObject> {
        // Method is simplified for better understanding the problem
        val inputObject = InputObject(
            param1,
            param2
        )
        return someOtherService.someMethod(inputObject)
}

open class InputObject(
    val param1: String,
    val param2: Int
)

So unit test looks like this:

... class test setup (Mock, InjectMocks, ExtendWith, ...) omitted for simplicity
@Test
fun `it should work`() {
    val inputObject = InputObject("SOME_PARAM", 0)
    whenever(someOtherService.someMethod(inputObject)).thenReturn(...some mocked data...)

    assertThat(myTestedObject.myMethod("SOME_PARAM", 0)).isNotNull // Some assertion
}

But problem is, I am getting Mockito error telling me, that object references for mocking someMethod are not the same (and I get why, two separate inputObjects are created, one in tested method and one in the test itself, and therefore when Mockito comparing object references, it does not know what to do with this situation).

I´ve tried to wrap inputObject into eq(inputObject) but that did not work either.

Is there any easy way to tell Mockito that I want it to check object content when trying to mock calling instead of comparing just references?


Solution

  • A simple solution would be to make InputObject a data class. Or make it implement equals/hashcode, so mockito can match the parameter on the mocked method.

    Alternatively you could use an Answer (1, 2) and verify there that InputObject has the correct values.