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

后端 未结 2 1759
小鲜肉
小鲜肉 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.

提交回复
热议问题