spring-boot - 使用 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
有任何想法吗?
解决方案
在 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)
}
推荐阅读
- sql - 连接后,表中的两行在另一个表中显示为两个不同的列
- java - 将不同子类的对象保存在一个集合中
- javascript - 如何在反应中使用钩子正确解构数组数组
- amazon-web-services - 为什么 terraform 会失败并显示“此处不需要名为“flow_log_destination_type”的参数”?
- python - 在没有 DRF 的情况下提交表单时在 Django 视图中生成 JWT 令牌
- google-chrome-extension - 如何使用 Chrome Devtools 协议接收嵌入式 iframe 的事件?
- javascript - 点击 ajax 结果总是更新最后点击的元素
- android-studio - 如何获取当前位置并将纬度和经度作为字符串?
- python - 打印数据框列和修改类型
- c# - 执行单击图片框