在 Junit 中捕获抛出的异常而没有 Throwable 块吞下它

Catch thrown exception in Junit without Throwable block swallowing it

我有一个 class 可以除以两个数字。当一个数字除以 0 时,它会抛出 ArithmeticException。但是当我对此进行单元测试时,在控制台上显示抛出 ArithmeticException,但我的测试失败并出现 AssertionError。我想知道是否有办法证明它在 Junit 中抛出了 ArithmeticException?
Example.java

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);
    }
}

我的实际代码不同,因为它有很多依赖项,我将我的要求简化为这个示例测试。请提出建议。

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);
}

您得到 AssertionError 因为预期的异常 ArithmeticException 没有被测试方法抛出。您需要让 ArithmeticException 传播出要测试的方法 divide。不要抓住它。不要在 divide.

抓到任何东西

JUnit 没有捕获异常,因为您已经在您的方法中捕获了它。如果您删除 "divide" 中的 try catch 块,JUnit 将捕获算术异常并且您的测试将通过

您的 divide() 方法正在捕获 ArithmeticException 但未对它执行任何操作(除了打印到控制台表明它已被捕获)。如果 divide() 方法应该抛出 ArithmeticException,那么您有两个选择:

  • 删除 divide() 方法中的 try/catch。一旦您尝试除以 0,它就会自动抛出 ArithmeticException,并且您的测试用例将在收到预期的异常 class 后通过。
  • 或者,在打印到控制台发现 ArithmeticException 被捕获后,将异常抛出 返回给调用方法。