When it comes to writing test cases for code, Mockito is one of the most common choices of developers. Then we face the question, how to use thenReturn() and thenAnswer() methods of Mockito? If you are facing this also, don't worry every one faces or has faced this question and we are here to solve it!! So, get set go...
Mockito is one of the most famous mocking framework for testing. Let us assume you already know about mockito. If not you can visit official mockito website before we proceed.
In Mockito insead of calling real method you can specify what to return or do when the method is called. This is called as the "Mocking".
There are different ways to specify mocked behavior. The most common ways are using thenReturn() and thenAnswer() methods.
Most of the times thenReturn() is used(which is fine) but some times we need to use thenAnswer().
When we should use thenReturn and when thenAnswer?
The simplest answer is - if you need fixed return value on method call then we should use thenReturn(…)
If you need to perform some operation or the value need to be computed at run time then we should use thenAnswer(…)
Let's look at the examples
Let's assume we need to return string value “Mockito” on getName() method call.
Mockito.when(mock.getName() ).thenReturn(“Mockito”)
If we need to return system time when we call getCurrentTime method we need
Mockito.when (mock.getCurrentTime() ).thenAnswer(I -> new Date() );
Now let's get into detail
Method thenReturn() needs a fixed object which will be returned when we call the method.
We can pass any type of object or value, the same value will be returned on method call.
Syntax: OngoingStubbing<T> thenReturn(T value);
Method thenAnswer needs the object of class implementing interface org.mockito.stubbing.Answer.
Answer is the functional interface having method answer(..)
The method answer() will be invoked when we call mocked method from mocked object.
We can use java 8 lambda feature for implementation of answer method.
Syntax: OngoingStubbing<T> thenAnswer(Answer<?> answer);
Basic difference between both is that thenRetun() will always return the same object.
Method thenAnswer will call the method from object every time we invoke the mocked method.
We can also pass function to thenRetun() for defining return value.
There can be 2 scenarios when we use thenAnswer or thenRetun with function.
- If function has fix return value, then there will be no difference in the result
eg. thenReturn(getUserName() );
And
thenAnswer(I -> getUserName() ); will function similar - If the return value is computed at run time depending on some parameters the there can be the different results
eg. thenReturn(getCurrentTime() );
And
thenAnswer(I -> getCurrentTime() );
(I) When function returns fixed value
Let's look at the example below, we have a method getName() to test in user class.
We will create a UserTest class for testing. Then we will mock getName() method.
Public class User {
public String getName() {
return this.name;
}
}
// This is the test class which will test the User class
public class UserTest {
private String dummyName() {
System.out.println(" #dummyName called");
return "Java";
}
@Test
public void thenReturnTest() throws Exception {
Tester mock = Mockito.mock(User.class);
System.out.println("------ Using: thenReturn------ ");
Mockito.when(mock.getName()).thenReturn(dummyName());
System.out.println(" -- method calls");
System.out.println("Call.1 : " + mock.getName());
System.out.println("Call.2 : " + mock.getName());
}
@Test
public void thenAnswerTest() throws Exception {
Tester mock = Mockito.mock(User.class);
System.out.println("------ Using: thenAnswer------ ");
Mockito.when(mock.getName()).thenAnswer(i -> dummyName());
System.out.println(" -- method calls");
System.out.println("Call.1 : " + mock.getName());
System.out.println("Call.2 : " + mock.getName());
}
}
// OUTPUT:
— #dummyName called
— method calls
Call.1 : Java
Call.2 : Java
— method calls
— #dummyName called
Call.1 : Java
— #dummyName called
Call.2 : Java
In the above example, we can see that getName() method returns same value in both the cases. However, the printed messages are different.
In case of thenRetun() use dummyName() method was executed before the actual call.
This is because as discussed above thenReturn() needs value hence at the time of initialization it is executed and returned value is used.
Also #dummyName called is printed twice in case of thenAnswer(). This is because every time we call mocked method, the function is executed.
(II) Return value is computed at run time
Let's look at the example below, we have a method getTime() to test in user class.
We will create a UserTest class for testing. Then will mock getTime() method.
Public class User {
public String getTime() {
return this.time;
}
}
public class UserTest {
private String now() {
Calendar now = Calendar.getInstance();
return now.get(Calendar.MINUTE) + " : " + now.get(Calendar.SECOND);
}
private String dummyGetTime() {
System.out.println(" #getTime called");
return now();
}
@Test
public void thenReturnTest() throws Exception {
Tester mock = Mockito.mock(User.class);
System.out.println("------ Using: thenReturn------ ");
Mockito.when(mock.getTime()).thenReturn(dummyGetTime());
System.out.println(" -- method calls");
System.out.println("Call.1> " + mock.getTime()+ " called at - " +now());
TimeUnit.SECONDS.sleep(5);
System.out.println("Call.2> " + mock.getTime()+ " called at - " +now());
}
@Test
public void thenAnswerTest() throws Exception {
Tester mock = Mockito.mock(User.class);
System.out.println("------ Using: thenAnswer------ ");
Mockito.when(mock.getTime()).thenAnswer(i -> dummyGetTime());
System.out.println(" -- method calls");
System.out.println("Call.1> " + mock.getTime()+ " called at : " +now());
TimeUnit.SECONDS.sleep(5);
System.out.println("Call.2> " + mock.getTime()+ " called at : " +now());
}
}
// OUTPUT: >
-- #getTime called
-- method calls
Call.1> 4 : 22 called at- 4 : 22
Call.2> 4 : 22 called at- 4 : 27
-- method calls
-- #getTime called
Call.1> 4 : 22 called at- 4 : 22
-- #getTime called
Call.2> 4 : 27 called at- 4 : 27
In the above example, we can see that getTime() method returns different values in case of thenAnswer() but same value in case of thenRetun().
In case of thenRetun() the value is calculated from now() method i.e. 4:22. This value is used in thenReturn() method every time getTime() function is called.
In case of thenAnswer(), every time we call mocked method getTime(), now() method is also called and returns the new value.
Performance impact
If the method returns simple fixed value we may not see any performance difference. However, if the method has database or network calls, there could be big performance difference.
If value is fixed then we should preferably use thenReturn() as this will only execute once.
Conclusion
We can conclude that the thenReturn() always returns same value whereas thenAnswer() returns the real time computed value.
Fast track reading
- If we need fixed return value on method call then we should use thenReturn(…)
- If value is computed at run time then we should use thenAnswer(…)
- thenReturn(T value) method needs fixed value which will be returned
- thenAnswer(Answer<T> answer) needs instance of Answer interface whose answer() method is called every time
- For fixed return value thenReturn() is perferable
Thanks for this concise article, it made me understand when to use which!
Two VERY minor corrections in the second code block you have 4 similar lines:
“System.out.println(“Call.1> ” + mock.getTime()+ ” called at – ” +now);”
The end of the lines should be “+ now());”
And the indentation looks a bit confusing because the methods start from the same indent as the class. Threw me off a bit at first.
Hello Tobias,
Thank you very much for your comment, we have tried to fixed it.
Feel free to add more comments if you have any suggestion, that helps our other readers.
Thank and Regards,
Stacktraceguru team
Nice article.