kotlin - 为什么 Mockito 会为此代码抛出“InvalidUseOfMatchersException”?
问题描述
我正在为用 Kotlin 1.5 编写的 Spring-Boot 项目编写测试。这段代码在测试运行时确实失败了InvalidUseOfMatchersException
,我很难弄清楚原因:
@SpringBootTest
@AutoConfigureMockMvc
internal class ControllerTest {
@Autowired
lateinit var mockMvc: MockMvc
@MockBean
lateinit var mockedAuthFilter: AuthFilter
@BeforeEach
fun setup() {
assertNotNull(mockedAuthFilter)
`when`(
mockedAuthFilter.shouldProceed(
any(HttpServletRequest::class.java),
any(AuthConfig::class.java)
)
).thenReturn(true)
}
@Test
fun `This call should return without an error`() {
mockMvc.perform(get("/api/entities")).andDo(print()).andExpect(status().isOk)
}
}
对于这个错误,我在网上能找到的只是你尝试了一个基本类型的参数匹配器——但这里不是这种情况。你有没有遇到过这个问题,你是如何解决的?
解决方案
据我了解,失败来自shouldProceed
方法本身导致的屏蔽空指针异常,该异常不允许使用空参数进行调用,这种情况在返回后设置模拟实例期间在 Mockito 内部发生any()
。
解决方案是不要将 Mockito 与 Kotlin 一起使用,而是使用 MockK 测试实用程序。
推荐阅读
- ios - 使用 Apple 登录后 AWS Cognito 令牌无效
- c# - C# 通用方法调用两个不同的服务
- android - 为什么这个错误发生在 android studio #flutter #androidstudio
- mysql - 如何优化Mysql窗口功能?
- keras - 获取keras编译模型损失函数
- azure-devops - 从 azure devops 获取给定测试用例的测试结果
- python - 从时间序列中识别事件
- flutter - 创建新版本后,Android 更改在 Google Play 中不可用
- sql - 如何从 SQL 中轮询新记录并使用 GraphQL(订阅)为它们提供服务?
- xml - 将 XML-Table 转换为字符映射