我有一個類將兩個數相除。當數字除以0時,它會拋出ArithmeticException。但是當我單元測試這個時,在控制檯上它顯示拋出了ArithmeticException,但是我的測試失敗並帶有AssertionError。我想知道是否有辦法證明它在Junit中拋出ArithmeticException?
Example.java在沒有可吞噬塊的Junit中捕獲拋出的異常
public class Example {
public static void main(String[] args)
{
Example ex = new Example();
ex.divide(10, 0);
}
public String divide(int a, int b){
int x = 0;
try{
x = a/b;
}
catch(ArithmeticException e){
System.out.println("Caught Arithmetic Exception!");
}
catch(Throwable t){
System.out.println("Caught a Different Exception!");
}
return "Result: "+x;
}
}
ExampleTest.java
public class ExampleTest {
@Test(expected=ArithmeticException.class)
public void divideTest()
{
Example ex = new Example();
ex.divide(10, 0);
}
}
我實際的代碼是不同的,因爲這有很大的依賴性,我simpflied我的要求,這個例子測試。請建議。
我不明白你說的是什麼。你能給我一個例子代碼。 – devlperMoose
@pavanbairu我已經添加了一個重構示例。 –
這有幫助。謝謝:-) – devlperMoose