2016-02-19 70 views
0

我有一個類將兩個數相除。當數字除以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我的要求,這個例子測試。請建議。

回答

2

divide不引發這個異常。

您的選項是

  • 提取物中的try/catch你可以從單元測試調用一個方法的內部。
  • 在單元測試中捕獲System.err並檢查它是否嘗試打印您期望的錯誤。

您可以提取使用IDE的方法是這樣

public static String divide(int a, int b){ 
    int x = 0; 
    try{ 
     x = divide0(a, b); 
    } 
    catch(ArithmeticException e){ 
     System.out.println("Caught Arithmetic Exception!"); 
    } 
    catch(Throwable t){ 
     System.out.println("Caught a Different Exception!"); 
    } 
    return "Result: "+x; 
} 

static int divide0(int a, int b) { 
    return a/b; 
} 

@Test(expected = ArithmeticException.class) 
public void testDivideByZero() { 
    divide0(1, 0); 
} 
+0

我不明白你說的是什麼。你能給我一個例子代碼。 – devlperMoose

+0

@pavanbairu我已經添加了一個重構示例。 –

+0

這有幫助。謝謝:-) – devlperMoose

1

你得到AssertionError因爲預期的異常,ArithmeticException,沒有得到由測試方法拋出。您需要讓ArithmeticException傳播出要測試的方法,divide。不要抓住它。不要在divide中捕捉任何東西。

+0

就像我在我的評論中提到的那樣,這只是我寫的一個示例代碼,可以讓您瞭解我的需求。但是,在我的實際代碼中,我需要在我的課程中捕獲該異常,並且單元測試也是一樣的。請建議。 – devlperMoose

+0

從您的問題描述中不清楚。你的'divide'方法需要返回一個'String'。讓它在你的'catch'塊中返回'e.getClass()。getName()'。然後讓你的測試方法'assertEquals'返回的字符串是'java.lang.ArithmeticException'。 – rgettman

1

JUnit沒有捕捉到異常,因爲您已經在您的方法中捕獲了它。如果您刪除「除法」中的try catch塊,JUnit將捕獲算術異常,並且您的測試將通過

+0

就像我在我的評論中提到的那樣,這只是我寫的一個示例代碼,可以讓您瞭解我的要求。但是,在我的實際代碼中,我需要在我的課程中捕獲該異常,並且單元測試也是一樣的。請建議。 – devlperMoose

1

您的divide()方法正在捕獲ArithmeticException但不對其執行任何操作(除了向控制檯打印它被捕獲)。如果divide()方法應該拋出ArithmeticException,那麼你有兩種選擇:

  • divide()方法中刪除try/catch語句。只要您嘗試除以0,它就會自動拋出一個ArithmeticException,並且您的測試用例會在接收到期望的Exception類時傳遞。
  • 或者,在打印控制檯後發現ArithmeticException被捕獲,丟棄,該異常備份到調用方法。
+0

第二個是個好主意,但即使在捕獲異常之後我也需要返回一些東西。彼得的例子符合我的要求。感謝您的幫助。 – devlperMoose

+0

您可能想澄清一下您的問題並更新測試用例以反映該問題。目前它期望拋出ArithmeticException(@Test(expected = ...)),並且它失敗了,因爲divide()方法吞嚥它而不是拋出它。 – Laj