Simulate first call fails, second call succeeds

前端 未结 5 1643
傲寒
傲寒 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:58

    From the docs:

    Sometimes we need to stub with different return value/exception for the same method call. Typical use case could be mocking iterators. Original version of Mockito did not have this feature to promote simple mocking. For example, instead of iterators one could use Iterable or simply collections. Those offer natural ways of stubbing (e.g. using real collections). In rare scenarios stubbing consecutive calls could be useful, though:

    when(mock.someMethod("some arg"))
       .thenThrow(new RuntimeException())
      .thenReturn("foo");
    
    //First call: throws runtime exception:
    mock.someMethod("some arg");
    
    //Second call: prints "foo"
    System.out.println(mock.someMethod("some arg"));
    

    So in your case, you'd want:

    when(myMock.doTheCall())
       .thenReturn("You failed")
       .thenReturn("Success");
    

提交回复
热议问题