Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito findByIdOrNull issue

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?

like image 597
MozenRath Avatar asked Jan 02 '20 10:01

MozenRath


1 Answers

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!

like image 73
Andy N Avatar answered Sep 18 '22 08:09

Andy N