In this post under Mockito, I will show with example how to stub mock object’s non-void non-static method to throw an exception.
In previous posts under Mockito, I have shown you how to stub mock object’s non-static void method to throw an exception by using Mockito’s “doThrow” method and passing the exception class object as argument.
Since in this case, it is a non-void method, we have to use Mockito’s “thenThrow” method and pass the exception class object that has to be thrown as an argument.
For our example I will use the below classes.
MyRandom
package package12;import java.util.Random;public class MyRandom { private Random random; public MyRandom() { random = new Random(); } public int nextInt() { return random.nextInt(100); }}
RandomGenerator
package package12;public class RandomGenerator { private MyRandom myRandom; public int generateRandomNumber() { return myRandom.nextInt(); } public MyRandom getMyRandom() { return myRandom; } public void setMyRandom(MyRandom myRandom) { this.myRandom = myRandom; }}
In the above code, “RandomGenerator” class is a dependent and “MyRandom” class is dependee.
We are writing test class for “RandomGenerator” class, so we will mock “MyRandom” class.
Below is the test class for your reference
RandomGeneratorTest
package package12;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 static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.Mockito.when;@ExtendWith(MockitoExtension.class)public class RandomGeneratorTest { @InjectMocks private RandomGenerator randomGenerator; @Mock private MyRandom myRandom; @Test public void testGenerateRandomNumber() { when(myRandom.nextInt()).thenThrow(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, ()->{ randomGenerator.generateRandomNumber(); }); }}
In the above code, at line 27, I telling Mockito framework that when “myRandom” mock object’s “nextInt” method is called then throw IllegalArgumentException exception.
In this way, we can stub mock object’s non-static non-void method to throw an exception.