0

Mockito – thenReturn or thenAnswer?

Mockito – thenReturn or thenAnswer?

This post demonstrates that thenReturn is designed to return the same value every time the stubbed method is invoked and that thenAnswer provides a way to vary the returned values after each method invocation. Generally, we use thenReturn to return “hardcoded” values; we use thenAnswer to use some complex logic to generate and return a value.

ThenReturn

The following example shows that thenReturn returns the same value from each invocation.

Java Codes

Below are the codes used for thenReturn.

SomeService1.java

This class represents some service injected to another class, SomeManager.

SomeManager.java

This class calls SomeService1‘s getSomethingRandom method twice when its processSomethingRandom method is invoked.

For our purpose, the method calls should print two different values. But with thenReturn, it prints the same value twice.

SomeManagerTest.java

This is our Test class. It has two (2) methods.

ThenAnswer

With thenAnswer, we can vary the value returned every time a stubbed method is invoke.

Java Codes

Below are the codes used for thenAnswer.

SomeManagerTest2.java

Download the codes

https://github.com/Turreta/Mockito-thenReturn-or-thenAnswer

References

http://site.mockito.org/

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert