In this article we will answer the question when to use the doAnswer() vs thenReturn() method in Mockito tests.
2. doAnswer() vs thenReturn()
The when(...).thenReturn(...) and doReturn(...).when(...) notations should be used in cases when we know exactly what will be the return value at the time we are mock a method call. This specified value will be returned when we invoke the mocked method.
Let's have a look at the example test:
The Answer is used when we need to do some additional calculations/actions when the mocked method is called. For exapmle, we could compute the return value based on input parameters.
We could also use doAnswer() when we want to stub a void method with a generic Answer.
Let's check the example:
In this example, we used an argument that was passed to the mocked method and calculate what result this method should return.
3. Conclusion
In this article, we compare doAnswer() and thenReturn() methods. We showed an example in which cases we should use them.
As usual, the code used in this article is available under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}