首页 > 解决方案 > 为什么 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)
    }
}

对于这个错误,我在网上能找到的只是你尝试了一个基本类型的参数匹配器——但这里不是这种情况。你有没有遇到过这个问题,你是如何解决的?

标签: kotlinmockitojunit5

解决方案


据我了解,失败来自shouldProceed方法本身导致的屏蔽空指针异常,该异常不允许使用空参数进行调用,这种情况在返回后设置模拟实例期间在 Mockito 内部发生any()

解决方案是不要将 Mockito 与 Kotlin 一起使用,而是使用 MockK 测试实用程序。


推荐阅读