使用 doThrow() 不抛出像 doThrow(null, NullPointerException.class) 这样的异常

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

我需要类似 doThrow(null, NullPointerException.class).when(myService).m1() 的东西,以便在第一次调用 void m1() 时不抛出异常,在第二次调用时抛出 NullPointerException

doThrow()不接受null.

我该如何解决这个问题?

这样试试:

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

对于非 void 方法,可以用同样的方式完成:

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