[英]Is there a way for a JUnit test to pass iff method implementation is correct AND recursive?
[英]Correct way to JUnit test divide() method
我有這個簡單的方法:
public int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by 0");
} else {
return a / b;
}
}
我想對 JUnit 進行測試。
我做了如下:
@Test(expected = ArithmeticException.class) // Expected this exc
public void testDivideWhenDivisorIsZero() {
int result = c.divide(1, 0);
}
它“返回”一條綠色條線(“測試成功完成”)。
try-catch
子句?編輯
此 JUnit 測試是否與以下測試等效?
@Test
public void testDivideWhenDivisorIsZero() {
try{
c.divide(1, 0);
fail("Expected ArithmeticException");
} catch(ArithmeticException e) {
}
}
你的測試看起來是正確的,你不應該在單元測試中使用try..catch
塊。 有很多方法,其中一種是你的。 但是對於您的方法,我想使用:
try {
return a / b;
} catch (ArithmeticException e) {
throw new ArithmeticException("Division by 0");
}
讓異常被拋出,並捕獲它。 它比在任何操作之前檢查值更干凈(這種情況很少發生)
你這樣做的方式對我來說似乎很好。
在這種情況下,它應該適合您的需要。 盡管如此,我個人更喜歡使用 try-catch-block 來完成。 正如你所提議的,這非常等價。 我認為如果你使用 try-catch-block 會有一些優勢。
首先,您可以斷言,如果拋出的異常的錯誤消息實際上與您已排除的一樣,而且您可以確定該異常實際上是在您的被測方法期間發生的,而不是在您的初始化邏輯期間發生的。 為了更清楚一點:
public int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by 0");
} else if(a<b){
//I know, that this condition is pretty senseless. It's for demonstration only.
throw new ArithmeticException("a is smaller than b");
} else{
return a / b;
}
}
然后您可以像這樣測試您的方法,並且可以確定拋出了正確的異常:
@Test
public void testDivideWhenDivisorIsZero() {
try{
c.divide(1, 2);
fail("Expected ArithmeticException");
} catch(Exception e) {
if(e instanceof ArithmeticException){
Assert.assertTrue(e.getMessage().equals("a is smaller than b"));
}else{
fail("The wrong Exception was thrown" + e.toString())
}
}
}
但正如我所說,您的嘗試完全符合需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.