
本文旨在介绍如何在 JUnit 中测试代码是否抛出预期的异常,并验证异常的类型和消息。文章详细讲解了使用 try-catch 块进行异常测试的方法,并展示了如何访问异常对象以进行更全面的验证。无论你使用的是哪个版本的 JUnit,都能找到适合你的解决方案。
在编写单元测试时,验证代码在特定情况下是否抛出预期的异常至关重要。JUnit 提供了多种方法来实现这一目标。本文将重点介绍使用 try-catch 块来测试异常,这种方法具有良好的灵活性和可读性。
使用 try-catch 块进行异常测试
这种方法的核心思想是在 try 块中执行可能抛出异常的代码,然后在 catch 块中捕获预期的异常,并进行断言验证。
以下是一个示例,演示如何使用 try-catch 块来测试一个除以零的操作是否抛出 ArithmeticException 异常,并且验证异常消息是否正确:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ExampleTest {
static class Example {
public static int divide(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("Denominator cannot be zero");
}
return numerator / denominator;
}
}
@Test
void testDivideByZero() {
try {
Example.divide(10, 0);
fail("Expected ArithmeticException was not thrown"); // 如果没有抛出异常,则测试失败
} catch (ArithmeticException e) {
assertEquals("Denominator cannot be zero", e.getMessage()); // 验证异常消息
}
}
}代码解释:
- @Test 注解: 标记该方法为一个测试用例。
- try 块: Example.divide(10, 0) 这行代码可能会抛出 ArithmeticException。
- fail("Expected ArithmeticException was not thrown"): 如果 Example.divide(10, 0) 没有抛出异常,则会执行这行代码,导致测试失败。这确保了只有在抛出异常时,测试才会继续到 catch 块。
- catch (ArithmeticException e) 块: 捕获 ArithmeticException 异常。
- assertEquals("Denominator cannot be zero", e.getMessage()): 断言捕获到的异常的消息是否与预期消息 "Denominator cannot be zero" 相匹配。
注意事项:
- fail() 方法: 在 try 块中调用 fail() 方法非常重要。如果没有抛出预期的异常,fail() 方法会立即导致测试失败,避免了错误的通过。
- 异常类型: 确保 catch 块捕获的是 预期 的异常类型。捕获错误的异常类型会导致测试无法正确执行。
- 异常消息: 验证异常消息可以确保异常是由特定原因引起的,并且可以提供更详细的错误信息。
访问异常对象
使用 try-catch 块的另一个优点是可以访问捕获到的异常对象。这使得你可以检查异常的更多属性,而不仅仅是消息。例如,你可以检查异常的堆栈跟踪,或者访问异常中包含的其他数据。
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ExampleTest {
static class CustomException extends Exception {
private final int errorCode;
public CustomException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
static class Example {
public static void processData(int value) throws CustomException {
if (value < 0) {
throw new CustomException("Value cannot be negative", 1001);
}
// ... 正常的处理逻辑 ...
}
}
@Test
void testProcessDataThrowsCustomException() {
try {
Example.processData(-5);
fail("Expected CustomException was not thrown");
} catch (CustomException e) {
assertEquals("Value cannot be negative", e.getMessage());
assertEquals(1001, e.getErrorCode()); // 验证自定义的 errorCode
}
}
}在这个例子中,我们定义了一个自定义的异常 CustomException,它包含一个 errorCode 字段。在测试中,我们不仅验证了异常消息,还验证了 errorCode 的值。
总结
使用 try-catch 块是在 JUnit 中测试异常的一种强大而灵活的方法。它允许你精确控制测试流程,验证异常类型和消息,并访问异常对象以进行更全面的验证。 这种方法适用于各种 JUnit 版本,并且易于理解和使用。记住始终使用 fail() 方法来确保在没有抛出预期异常时测试失败,并仔细选择要捕获的异常类型。








