第一次调用模拟方法时如何只抛出异常? [英] How to only throw exception when the mocked method is called for the first time?

查看:16
本文介绍了第一次调用模拟方法时如何只抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以多次调用的模拟对象的方法(想想递归).方法定义如下:

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();

不过,这会使该方法在每次调用时都抛出此异常.例如,我怎样才能使它只在第一次和第三次被调用时抛出它?这意味着,例如,第二次和第四次它只是返回而不抛出异常.请注意,我不是 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.

推荐答案

我想通了(Igor 提供了一些提示).这就是你存根连续的 void 方法调用的方式:

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();

感谢伊戈尔!

这篇关于第一次调用模拟方法时如何只抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆