java - Mockito findByIdOrNull 问题
问题描述
我有一个这样的测试:
@Test
fun `can execute`() {
whenever(countryRepository.findByIdOrNull("DE")).thenReturn(germany)
underTest.execute()
}
此测试失败并显示以下错误消息:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Country cannot be returned by findById()
findById() should return Optional
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
很确定这可能是 Mockito 的问题,因为我没有使用findbyId
但使用findByIdOrNull
它更适合 kotlin。我不想更改代码来修复测试。
你能帮我解决这个问题或解决这个问题吗?
解决方案
显然:
Mockito 不支持模拟静态方法,至少在不久的将来不会。 https://github.com/mockito/mockito/issues/1481
所以扩展代码实际上是在执行而不是模拟。
一种解决方案可能是只让代码执行,而不是findByIdOrNull
模拟只是模拟底层findById
(返回一个可选的)。
编辑
..或按照链接建议使用MockK !
推荐阅读
- uwp - 评价 Uwp 应用程序 - 商店中显示未知用户
- autodesk-forge - 在 v7 中使用 setViewCube 更新视图
- google-chrome-extension - 内容脚本在一段时间后停止收听后台脚本
- python - 删除列上有多个条件的行
- mysql - 在 PuTTy SSH 中的 Laravel 项目中获取 wordpress 的子域 URL
- java - 对 RestTemplate 的嵌套对象进行 URL 编码
- reporting-services - 按日期链接行
- karate - 简单的 POST 请求在空手道 API 中不起作用,在 POSTMAN 中也可以正常工作,请在“请求”中提出任何错误
- ios - PHImageManager requestImageData 消耗大量内存
- filter - 使用用户定义的属性过滤测量的最佳实践