[英]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.