[英]How to doThrow or thenThrow on method that returns void and throws an exception
我有一个返回无效的方法process
,并且可能会引发异常。 我想验证其他方法在调用process
如何run
并处理异常(如果发生)。
我尝试使用doThrow()
但是它告诉“已检查的异常对该方法无效!”。 然后,我尝试使用thenThrow()
但它需要一个不无效的函数。
码:
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 ...
我希望测试会成功。
这是告诉模拟程序抛出异常的正确方法:
Mockito.doThrow(new SomeException()).when(mock).doSomething()
如Hulk在评论中所述,此异常需要与方法签名匹配,否则,您将获得MockitoException("Checked exception is invalid for this method!")
您可以通过抛出某种RuntimeException
来解决该异常。 最后,您应该尝试避免使用泛型Exception
。 抛出适当的命名异常要有用得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.