71

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 ?

1
  • You mean when(repository.merge(any(SomeEntity.class))).thenReturn(entity); ? Oct 2, 2014 at 13:32

3 Answers 3

134

You can use the Mockito shipped answers:

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

Where AdditionalAnswers.returnsFirstArg() could be statically imported.

4
  • 2
    Nice! I didn't expect this to be common enough to be built in, never mind "returnsSecondArg", etc. I also like using the then() alias here as it reads better. Oct 2, 2014 at 17:23
  • Yes ;) we've introduced then alias to read better when used in combination with static factory method for custom answers.
    – bric3
    Oct 3, 2014 at 11:14
  • @MarkPeters, AdditionalAnswers is for "less common answers", it says in the documentation
    – smac89
    Aug 7, 2017 at 23:04
  • 1
    @smac89 but common enough ;)
    – bric3
    Aug 8, 2017 at 7:44
56

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.

3
  • 26
    Already exists in mockito : AddtionalAnswers.returnsFirstArg()
    – bric3
    Oct 2, 2014 at 17:11
  • 6
    You can still shorten the code with thenAnswer(i -> i.getArguments()[0]). Great solution, and BTW the AddtionalAnswers.returnsFirstArg() is giving me some errors.
    – EliuX
    Jun 19, 2017 at 20:28
  • Great, this give me an ocean of opportunities. Thanks
    – Guilherme
    Oct 16, 2019 at 12:59
12

It can be done easy with Java 8 lambdas:

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.