【问题标题】:Mockito findByIdOrNull issueMockito findByIdOrNull 问题
【发布时间】:2020-01-02 10:58:12
【问题描述】:

我有一个这样的测试:

    @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。我不想更改代码来修复测试。

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

【问题讨论】:

    标签: java unit-testing jpa kotlin mockito


    【解决方案1】:

    显然:

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

    所以extension code 实际上是在执行而不是模拟。

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

    编辑

    ..或使用链接建议的MockK

    【讨论】:

      【解决方案2】:

      findById 方法的返回类型必须是 Optional (Java 8)。您可以指定返回一个可选的国家/地区,如下所示。

      Optional<Country> countryOptional = Optional.ofNullable(country);
      when(findById(any())).thenReturn(countryOptional);
      

      希望对您有所帮助。

      【讨论】:

      • 问题是我不是在嘲笑findById,而是findByIdOrNull
      猜你喜欢
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多