In this article, we will show how to configure the method call to throw an exception using Mockito. We will present two approaches: one for methods that returns some value and one for void methods - there are some differences in the implementation.
2. Example service class
We will be testing simple ThrowingService that has two methods:
someVoidMethod(int value) - this method doesn't return any value,
someNotVoidMethod(int value) - method that returns int value.
3. Testing void method
In the following JUnit test we show how to change the behavior of the someVoidMethod(..) method in ThrowingService using Mockito:
In the first test we used the Mockito statement doThrow(...).when(...).method(...) to configured someVoidMethod to throw IllegalArgumentException when called with argument 0.
Note that we could not use the statement when(...).thenThrow(...) for methods that do not return any value.
The following code WILL NOT COMPILE.
4. Testing method that returns int value
When testing not void methods we could actually decide what approache is better for us, because both will work in the same way: