gpt4 book ai didi

java - Mockito findByIdOrNull 问题

转载 作者:行者123 更新时间:2023-12-01 14:17:23 32 4
gpt4 key购买 nike

我有一个这样的测试:

    @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 doesn't support the mocking of static methods, at least not in the near future. https://github.com/mockito/mockito/issues/1481



所以 extension code实际上是被执行而不是被 mock 。

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

编辑

..或使用 MockK正如链接所暗示的那样!

关于java - Mockito findByIdOrNull 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562177/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com