how to skip fist when-then call in junit

60 Views Asked by At

I want to write a Junit test for a Java code similar to the code below. In the code, method() is called 2 times. In my Junit test, I have something like this when(method()).thenThrow(exception); but I want this when-then to be triggered on the 2nd method() call, and not on the 1st method() call. So, how can I do that?

class Example {
    public void example() {
        OtherClass.method(); //1st method call
        /*
        * doing something
        */
        OtherClass.method(); //2nd method call
    }
}
2

There are 2 best solutions below

0
tgdavies On BEST ANSWER

You can repeat Mockito's do...() methods when you mock a void method:

        doNothing().doThrow(new RuntimeException("test")).when(mock).method();

The effects will happen in sequence if there are multiple calls to method.

0
Demneru On

You can use @Spy for your instance what are testing.

Spies are like mocks but you can stub some methods of the same class what you are testing --well this answer was for your first question

After edit, you can just chain the second stub

when(method()).thenThrow(exception).thenThrow(exception);