2016-02-19 71 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