Reputation: 851
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
?
Upvotes: 73
Views: 39374
Reputation: 42223
You can use the Mockito shipped answers:
when(mock.something()).then(AdditionalAnswers.returnsFirstArg())
Where AdditionalAnswers.returnsFirstArg()
could be statically imported.
Upvotes: 139
Reputation: 81074
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.
Upvotes: 60
Reputation: 833
It can be done easy with Java 8 lambdas:
when(mock.something(anyString())).thenAnswer(i -> i.getArguments()[0]);
Upvotes: 13