如何仅在第一次调用模拟方法时抛出异常?
我有一个可以多次调用的模拟对象的方法(想想递归)。该方法的定义如下:
public void doCommit() { }
为了告诉它失败,我使用了这个约定:
doThrow(new RuntimeException()).when(mMockedObject).doCommit();
但这使得该方法每次调用时都会抛出此异常。例如,我怎样才能使它只在第一次和第三次被调用时抛出它?这意味着,例如,第二次和第四次它只是返回而不抛出异常。请注意,我不是 doCommit() 的作者,也没有可以更改的源代码。
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() { }
In order to tell it to fail I use this convention:
doThrow(new RuntimeException()).when(mMockedObject).doCommit();
This though, makes the method throw this exception EVERY time it is called. How can I make it so that it only, for example, throws it the first and third time it is called? Which means that, for example, the second and forth time it just returns without throwing an exception. Please note that I am not the author of doCommit(), nor do I have source code that I can change.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想通了(有伊戈尔的一些提示)。这就是存根连续 void 方法调用的方法:
谢谢 Igor!
I figured it out (with some hints from Igor). This is how you stub consecutive void method calls:
thanks Igor!
阅读存根连续调用 doco,了解一些内容像这样可能会这样做:
如果您不想实际调用底层方法,那么您应该使用
thenAnswer
而不是thenCallRealMethod
方法并提供一个空的存根实现。Reading Stubbing Consecutive Calls doco, something like this might do it:
If you don't want to actually call the underlying method then you should use
thenAnswer
instead ofthenCallRealMethod
method and provide an empty stub imlementation.