Simulate first call fails, second call succeeds

前端 未结 5 1597
傲寒
傲寒 2021-01-30 15:24

I want to use Mockito to test the (simplified) code below. I don\'t know how to tell Mockito to fail the first time, then succeed the second time.

for(int i = 1;         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-30 15:56

    To add on to this and this answer, you can also use a loop to chain the mocked calls. This is useful if you need to mock the same thing several times, or mock in some pattern.

    Eg (albeit a farfetched one):

    import org.mockito.stubbing.Stubber;
    
    Stubber stubber = doThrow(new Exception("Exception!"));
    for (int i=0; i<10; i++) {
        if (i%2 == 0) {
            stubber.doNothing();
        } else {
            stubber.doThrow(new Exception("Exception"));
        }
    }
    stubber.when(myMockObject).someMethod(anyString());
    

提交回复
热议问题