在单元测试中,测试方法是否抛出预期的异常非常重要。JUnit 提供了多种方法来测试异常,包括:
1. 使用 try-catch 语句
最简单的方法是使用 try-catch 语句显式检查异常。
@Test
public void testMethodThrowsException() {
try {
// 调用可能抛出异常的方法
methodUnderTest();
fail("Expected exception was not thrown");
} catch (Exception e) {
// 验证异常类型和消息
assertEquals(ExpectedException.class, e.getClass());
assertEquals("Expected error message", e.getMessage());
}
}
2. 使用 assertThrows() 方法(JUnit 5 及更高版本)
assertThrows()
方法提供了一种更简洁的方式来测试异常。
@Test
public void testMethodThrowsException() {
assertThrows(ExpectedException.class, () -> methodUnderTest());
}
3. 使用 ExpectedException 规则(JUnit 4)
ExpectedException
规则允许你在测试方法周围创建一个上下文,其中会自动捕获异常并进行验证。
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testMethodThrowsException() {
thrown.expect(ExpectedException.class);
thrown.expectMessage("Expected error message");
// 调用可能抛出异常的方法
methodUnderTest();
}
4. 使用 Hamcrest 匹配器(JUnit 4 和 5)
Hamcrest 提供了 isA()
和 hasMessage()
匹配器,可用于验证异常类型和消息。
@Test
public void testMethodThrowsException() {
assertThatExceptionOfType(ExpectedException.class)
.isThrownBy(() -> methodUnderTest())
.withMessage("Expected error message");
}
示例
以下示例演示如何使用 assertThrows()
方法测试方法是否抛出 IllegalArgumentException
:
@Test
public void testMethodThrowsIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> methodUnderTest(null));
}
结论
JUnit 提供了多种方法来测试方法是否存在异常。选择哪种方法取决于你的喜好和测试用例的具体要求。