In this article, we will focus on a case when the original method is called even though we use Mockito to configure a different behavior.
2. Testing class
Let's use a simple class ThrowingService to show our case:
This class has two methods: one that returns the int value and one void method.
3. JUnit test
In the following example test we used when(...).thenReturn(...) statement to change the return value when called someNotVoidMethod(...) method on ThrowingService object:
Unfortunately, the original throwingService.someNotVoidMethod(0) method will be called in this case and the ArithmeticException will be thrown because we send 0 as an argument to that method, and we cannot be dived by zero.
Note that we will not have that issue with mock. The following code will not throw an ArithmeticException:
How to fix our test?
We need to use doReturn(...).when(...).method(...):
The important thing to remember here is:
Please use doReturn() family of methods when stubbing a method using spies,
when(...) would result in calling the actual method that can throw exceptions.
In this article, we presented a case where a real method on a spied object was called when we try to configure it using Mockito.