Mockito - returning the same object as passed into method

JavaMockito

Java Problem Overview


Let's imagine I have a following method in some service class:

public SomeEntity makeSthWithEntity(someArgs){
	SomeEntity entity = new SomeEntity();
	/**
	 * here goes some logic concerning the entity
	 */
	return repository.merge(entity);
}

I'd like to test the behaviour of this method and thus want to mock the repository.merge in following manner:

when(repository.merge(any(SomeEntity.class))).thenReturn(objectPassedAsArgument);

Then mocked repository returns that what makesSthWithEntity passed to it and I can easily test it.

Any ideas how can I force mockito to return objectPassedAsArgument ?

Java Solutions


Solution 1 - Java

You can use the Mockito shipped answers:

when(mock.something()).then(AdditionalAnswers.returnsFirstArg())

Where AdditionalAnswers.returnsFirstArg() could be statically imported.

Solution 2 - Java

You can implement an Answer and then use thenAnswer() instead.

Something similar to:

when(mock.someMethod(anyString())).thenAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
        return invocation.getArguments()[0];
    }
});

Of course, once you have this you can refactor the answer into a reusable answer called ReturnFirstArgument or similar.

Solution 3 - Java

It can be done easy with Java 8 lambdas:

when(mock.something(anyString())).thenAnswer(i -> i.getArguments()[0]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLechPView Question on Stackoverflow
Solution 1 - JavaBriceView Answer on Stackoverflow
Solution 2 - JavaMark PetersView Answer on Stackoverflow
Solution 3 - JavaFilomatView Answer on Stackoverflow