Mockito : What is the difference between 'thenReturn()' and 'thenAnswer()'?

Viewed 726

Both the way I can call the method and apply the logic,

Example

thenAnswer(val -> {
            //logic
            return newValue;
        });


thenReturn(callMethod1(obj));

obj callMethod1(obj){

//Logic
return obj;
}```
2 Answers

thenReturn() needs an object to return, while thenAnswer() needs the object of the class implementing interface.
So, if you need to return a fixed value, the correct method to use is thenReturn(), but if you need to do some kind of operations with the object you're returning, then you should use thenAnswer(), which will invoke an Answer instance.
In resume, it's just a matter of implementation, and choosing one or another just depends on what purposes you have.

thenReturn, as the name says, just returns some value when the mocked condition occurs.

thenAnswer invokes the answer method of an Answer instance, and allows you to execute some arbitrary code when the condition occurs.

Related