java如何在返回void并引发异常的方法上doThrow或thenThrow
我有一个方法process
,它返回void并可能引发异常。我想验证其他方法run
在调用process
时的行为,并在异常发生时处理异常
我尝试过使用doThrow()
,但它告诉我“Checked exception对此方法无效!”。然后我尝试使用thenThrow()
,但它需要一个not void函数
代码:
public void run() {
for (var billet : getBillets()) {
try {
process(billet);
billet.status = "processed";
} catch (Exception e) {
billet.status = "error";
}
billet.update();
}
}
public void process(Billet billet) throws Exception {
var data = parse(billet.data); // may throw an exception
var meta = data.get("meta"); // may throw an exception
// ... more parsing ...
new Product(meta).save();
new Item(meta).save();
// ... more operations ...
};
测试:
var billet1 = new Billet();
var billet2 = new Billet();
doThrow(new Exception()).when(myInctance).process(billet2);
myInctance.run();
assertEquals("processed", billet1.status);
assertEquals("error", billet2.status);
// ... some checks ...
我希望这次试验会成功
# 1 楼答案
这是告诉mock抛出异常的正确方法:
正如Hulk在评论中所说的,这个异常需要与方法签名匹配,否则,您将得到一个
MockitoException("Checked exception is invalid for this method!")
您可以通过抛出某种类型的
RuntimeException
来绕过该异常。最后,应该尽量避免使用泛型Exception
。抛出一个适当的命名异常要有用得多