Software Development

Should you use Mockito thenReturn or thenAnswer?

Should you use Mockito thenReturn or thenAnswer? It depends! The thenReturn returns the same value in every method run; while the thenAnswer does not. We use the former to return hard-coded values; while we use the latter for derived values.

Mockito ThenReturn

Below is a screenshot that shows the output from thenReturn. Each of the first 4 lines uses thenReturn. The testNonRandom method returns 1 twice. The testRandom returns the same UUID twice.

Mockito ThenReturn returns the same value everytime!

Java Codes

The following codes use thenReturn.

SomeService1.java

We inject this service to another class and we want to mock its method.

SomeManager.java

This calls getSomethingRandom twice within processSomethingRandom. The calls should print two different values. We can use this class for both Mockito thenReturn or thenAnswer.

Unit Test – SomeManagerTest.java

This is our Test class. It has 2 methods. One mocks another method to return a hard-coded value; while the other to return random value.

Mockito ThenAnswer

Below is a screenshot that shows the output from thenAnswer.

Mockito ThenAnswer returns derived values!

Java Codes

Below are the codes using thenAnswer. They use the Answer interface. They override its single method to return a derive value. However, we can use Lamda expression.

SomeManagerTest2.java

Using Mockito thenReturn or thenAnswer depends on your needs. If you need work with static values, use thenReturn. If you need to use dynamic or derived values, use thenAnswer.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like