首页 > 解决方案 > 使用 Mockito 模拟扩展功能

问题描述

如何使用 Mockito 测试扩展功能?它似乎不能很好地工作。

这是我的扩展功能

fun <T> CrudRepository<T, String>.findOneById(id: String): T? {
    val o = findById(id)
    return if (o.isPresent) o.get() else null
}

这就是我要测试的

  @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")
    }

但是前面的测试会引发以下错误

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
IslandEntity cannot be returned by findById()
findById() should return Optional

有任何想法吗?

标签: spring-bootkotlinmockito

解决方案


在 mockito-kotlin 的帮助下,可以像这样模拟实例扩展函数:

data class Bar(thing: Int)

class Foo {
   fun Bar.bla(anotherThing: Int): Int { ... }
}

val bar = Bar(thing = 1)
val foo = mock<Foo>()

with(foo) {
  whenever(any<Bar>().bla(any()).doReturn(3)
}

verify(foo).apply {
  bar.bla(anotherThing = 2)
}

推荐阅读