In this post under Mockito, I will show with example how to stub a mock object’s non-static non-void method to return different values when called consecutively.
For our example, we will use the below class
MyRandom
package package11;import java.util.Random;public class MyRandom { private Random random; public MyRandom() { random = new Random(); } public int nextInt() { return random.nextInt(100); }}
RandomGenerator
package package11;import java.util.Random;public class RandomGenerator { private Random random; public int generateRandomNumber() { return random.nextInt(100); } public Random getRandom() { return random; } public void setRandom(Random random) { this.random = random; }}
As shown in the above code, “RandomGenerator” class uses “MyRandom” class. So “RandomGenerator” becomes the dependent and “MyRandom” becomes the dependee.
We need to write test class for “RandomGenerator” so we mock “MyRandom”, which is as shown below
RandomGeneratorTest
package package11;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import java.util.Random;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.Mockito.when;@ExtendWith(MockitoExtension.class)public class RandomGeneratorTest { @InjectMocks private RandomGenerator randomGenerator; @Mock private MyRandom myRandom; @Test public void testGenerateRandomNumber1() { when(myRandom.nextInt()).thenReturn(200).thenReturn(300).thenReturn(400); assertEquals(200, randomGenerator.generateRandomNumber()); assertEquals(300, randomGenerator.generateRandomNumber()); assertEquals(400, randomGenerator.generateRandomNumber()); } @Test public void testGenerateRandomNumber2() { when(myRandom.nextInt()).thenReturn(200, 300, 400); assertEquals(200, randomGenerator.generateRandomNumber()); assertEquals(300, randomGenerator.generateRandomNumber()); assertEquals(400, randomGenerator.generateRandomNumber()); }}
In the above code, at line 23, I am telling Mockito that when “myRandom” object’s “nextInt” method is called 3 times, return 200, then 300, and at the end 400.
We can configure the same thing in another way which is shown at line 32.
In this way, we can stub a mock object’s non-static non-void method to return different values when called consecutively.