use doThrow() to NOT throw an exception like doThrow(null, NullPointerException.class)

Viewed 155

I need something like doThrow(null, NullPointerException.class).when(myService).m1() to throw no exception on the first call of void m1() and a NullPointerException on the second call.

doThrow() does not accept null.

How can I solve this?

1 Answers

Try like this:

doNothing().doThrow(NullPointerException.class).when(myService).m1();

For non-void methods it can be done the same way:

 when(obj.methodName()).thenThrow(RuntimeException.class)
                       .thenReturn(something);
Related