温馨提示×

如何使用JUnit测试异常

小樊
86
2024-06-18 16:17:58
栏目: 编程语言

在JUnit中,测试异常的方法主要是使用@Test注解中的expected参数来捕获异常。下面是一个示例代码:

import org.junit.Test;

public class ExceptionTest {

    @Test(expected = ArithmeticException.class)
    public void testArithmeticException() {
        int result = 1 / 0;
    }

    @Test
    public void testNullPointerException() {
        try {
            String str = null;
            int length = str.length();
        } catch (NullPointerException e) {
            // 可以在catch块中添加断言,检查异常是否符合预期
        }
    }
}

在第一个测试方法中,我们使用了@Test(expected = ArithmeticException.class)来捕获ArithmeticException异常。如果代码中抛出了ArithmeticException异常,测试将会通过。如果代码没有抛出异常,测试将会失败。

在第二个测试方法中,我们使用了try-catch块来捕获NullPointerException异常,并且可以在catch块中添加断言,检查异常是否符合预期。

除了使用expected参数和try-catch块外,JUnit还提供了@Rule注解和ExpectedException规则类来测试异常。可以根据具体的需求选择合适的方式来测试异常。

0