How can I mock an extension function in Kotlin with Mockito? It doesn't seem to work nicely.
This is my extension function
fun <T> CrudRepository<T, String>.findOneById(id: String): T? {
val o = findById(id)
return if (o.isPresent) o.get() else null
}
And this is what my test case
@Test
fun getIslandById() {
//given
BDDMockito.given(islandRepository.findOneById("islandId1"))
.willReturn(IslandEntity(tileList, "1", "islandId1")) //findOneById is my extension function
//when
val island = islandService.getIslandById("islandId1")
//then
Assertions.assertThat(island?.id).isEqualTo("islandId1")
}
But the preceeding test throws the following error
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
IslandEntity cannot be returned by findById()
findById() should return Optional
Any ideas for a workaround? Could this be a bug?
Kotlins extension functions are resolved statically. The Docs say:
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
We would like to emphasize that extension functions are dispatched statically, i.e. they are not virtual by receiver type. This means that the extension function being called is determined by the type of the expression on which the function is invoked, not by the type of the result of evaluating that expression at runtime.
Mockito doesn't support the mocking of static methods, at least not in the near future.
The workaround is to use Mockk which supports your use case, and integrates much better with Kotlin.
Most helpful comment
Kotlins extension functions are resolved statically. The Docs say:
Mockito doesn't support the mocking of static methods, at least not in the near future.
The workaround is to use Mockk which supports your use case, and integrates much better with Kotlin.