Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Is it possible to chain multiple thenThrow() calls for different exceptions


Is it possible to chain multiple thenThrow() calls for different exceptions


Yes, it is possible to chain multiple `thenThrow()` calls for different exceptions in Mockito, but it does not work as chaining multiple `thenReturn()` calls. When you chain multiple `thenThrow()` calls, the first exception will be thrown when the method is invoked, but subsequent calls to `thenThrow()` do not override the previous stubbing in the way that `thenReturn()` does. Instead, you can use `thenThrow(Throwable... throwables)` to specify multiple exceptions that will be thrown consecutively when the mocked method is invoked.

Here's how you can achieve this:

Using `thenThrow(Throwable... throwables)`

You can pass multiple exceptions to `thenThrow()` as varargs. Each exception will be thrown consecutively when the method is invoked:

java
Mockito.when(myClass.myMethod())
       .thenThrow(new Exception1(), new Exception2(), new Exception3());

In this case, `Exception1` will be thrown on the first call, `Exception2` on the second call, and `Exception3` on the third call. After that, no exception will be thrown.

Using Chained `thenThrow()` Calls

While chaining multiple `thenThrow()` calls is technically possible, it does not behave as expected because the first `thenThrow()` call sets the behavior for the mock, and subsequent calls do not override it in the same way as `thenReturn()` does. However, you can use `thenThrow()` multiple times in a chain for different method calls or stubs:

java
Mockito.when(myClass.method1()).thenThrow(new Exception1());
Mockito.when(myClass.method2()).thenThrow(new Exception2());

But for the same method, you should use the varargs approach as shown above.

Using `doThrow()` and `doAnswer()`

If you need more complex behavior, such as throwing exceptions based on the number of calls or other conditions, you can use `doAnswer()` with an `Answer` implementation:

```java
Mockito.doAnswer(new Answer() {
private int count = 0;
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (count++