Mockito is a popular Java library for creating mock objects in unit testing. In some cases, we might need to simulate the behavior of a mocked object whose values keep changing.

In this article, we will see how to use Mockito to return different values when a mocked method is called multiple times.

Create the mock object

Let us get started by importing the required dependencies & creating a mock object using the Mockito.

import org.mockito.Mockito;

// Create a mock object of a class/interface
SomeClass mockObject = Mockito.mock(SomeClass.class);

Return different values

In order to return different values on different calls of the same method, we can use the thenReturn() method multiple times as shown in the following example.

// Return "firstValue" when the method is called the first time
Mockito.when(mockObject.someMethod()).thenReturn("firstValue");

// Return "secondValue" when the method is called the second time
Mockito.when(mockObject.someMethod()).thenReturn("secondValue");

In the above example, the someMethod() of the mock object mockObject will return “firstValue” the first time it’s called and “secondValue” the second time it’s called.

Returning sequence of values

You can also return a sequence of different values on successive method calls. To do that, use the thenReturn() method with multiple arguments, as shown in the below example.

// Return "value1", "value2", and "value3" on successive method calls
Mockito.when(mockObject.someMethod())
       .thenReturn("value1", "value2", "value3");

References:

https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html

Categorized in:

Tagged in:

,