I have a test like this:
@Test
fun `can execute`() {
whenever(countryRepository.findByIdOrNull("DE")).thenReturn(germany)
underTest.execute()
}
This test fails with the following error message:
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.
Pretty sure this might be an issue with Mockito as I am not using findbyId
but using findByIdOrNull
as this is more suitable for kotlin. I do not want to change the code to fix a test.
can you please help me with a way to get rid of this issue or to work around this?
Apparently:
Mockito doesn't support the mocking of static methods, at least not in the near future. https://github.com/mockito/mockito/issues/1481
So the extension code is actually being executed rather than mocked.
One resolution may be to just let the code execute and instead of mocking findByIdOrNull
just mock the underlying findById
(to return an optional).
Edit
..or use MockK as the link suggests!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With