How to only throw exception when the mocked method is called for the first time?

后端 未结 2 1758
小鲜肉
小鲜肉 2021-02-06 21:30

I have a method of a mocked object that can be called multiple times (think recursion). The method is defined like this:

public void doCommit() { }
相关标签:
2条回答
  • 2021-02-06 21:53

    Reading Stubbing Consecutive Calls doco, something like this might do it:

    when(mMockedObject.doCommit())
      .thenThrow(new RuntimeException())
      .thenCallRealMethod() 
      .thenThrow(new RuntimeException())
      .thenCallRealMethod();
    

    If you don't want to actually call the underlying method then you should use thenAnswer instead of thenCallRealMethod method and provide an empty stub imlementation.

    0 讨论(0)
  • 2021-02-06 22:05

    I figured it out (with some hints from Igor). This is how you stub consecutive void method calls:

    doThrow(new RuntimeException()).doNothing().doThrow(...).doNothing().when(mMockedObject).doCommit();
    

    thanks Igor!

    0 讨论(0)
提交回复
热议问题