Enterprise Java

Mockito ‘thenReturn’ vs Mockito ‘thenAnswer’

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.

1
Mockito.when(mock.getName() ).thenReturn(“Mockito”)

If we need to return system time when we call getCurrentTime method we need

1
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.

1
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.

1
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.

  1. 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
  2. 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.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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:

—— Using: thenReturn——
— #dummyName called
— method calls
Call.1 : Java
Call.2 : Java
—— Using: thenAnswer——
— 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.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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: >

—— Using: thenReturn——
— #getTime called
— method calls
Call.1> 4 : 22 called at- 4 : 22
Call.2> 4 : 22 called at- 4 : 27
—— Using: thenAnswer——
— 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

Published on Java Code Geeks with permission by Stacktraceguru, partner at our JCG program. See the original article here: Mockito ‘thenReturn’ vs Mockito ‘thenAnswer’

Opinions expressed by Java Code Geeks contributors are their own.

Stacktraceguru

Stacktraceguru is an educational website. This website helps software programmers to learn and clarify concepts.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button