首页 > 解决方案 > 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。我不想更改代码来修复测试。

你能帮我解决这个问题或解决这个问题吗?

标签: javaunit-testingjpakotlinmockito

解决方案


显然:

Mockito 不支持模拟静态方法,至少在不久的将来不会。 https://github.com/mockito/mockito/issues/1481

所以扩展代码实际上是在执行而不是模拟。

一种解决方案可能是只让代码执行,而不是findByIdOrNull模拟只是模拟底层findById(返回一个可选的)。

编辑

..或按照链接建议使用MockK !


推荐阅读