Mockito AdditionalAnswers

Sometimes you use a framework for years, and then discover something new that it can do.

I had one of those moments today with Mockito.

I have an API that I am mocking, where I need to capture the argument passed in for further testing, that had a line that ended up looking something like this:

when(mockRepository.save(captor.capture())).thenReturn(captor.capture());

This is actually incorrect Mockito syntax. The captor.capture() doesn’t go inside a “thenReturn” statement.

The underlying API (Spring-Data) has methods that typically return the first parameter:

/**
 * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
 * entity instance completely.
 * 
 * @param entity
 * @return the saved entity
 */
 <S extends T> S save(S entity);

The more correct way (aside from refactoring how the code works) to use Mockito would be do use thenAnswer(Answer<>), instead of thenReturn. Since we don’t want to clutter our code with an additional 5 lines for an inline Answer instance, there is a helper class in Mockito: AdditionalAnswers.

The simplified solution:

when(mockedRepository.save(captor.capture())).thenAnswer(returnsArgAt(0));

Leave a Reply