捕获预期的异常
可以在没有任何 try catch
块的情况下轻松捕获异常。
public class ListTest {
private final List<Object> list = new ArrayList<>();
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
list.get(0);
}
}
当你不希望/需要检查抛出的异常所携带的消息时,上面的示例应该足以满足更简单的情况。
如果要检查有关异常的信息,可能需要使用 try / catch 块:
@Test
public void testIndexOutOfBoundsException() {
try {
list.get(0);
Assert.fail("Should throw IndexOutOfBoundException");
} catch (IndexOutOfBoundsException ex) {
Assert.assertEquals("Index: 0, Size: 0", ex.getMessage());
}
}
对于此示例,你必须注意始终添加 Assert.fail()
以确保在未抛出异常时测试将失败。
对于更详细的案例,JUnit 有 ExpectedException
@Rule
,它也可以测试这些信息并按如下方式使用:
public class SimpleExpectedExceptionTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
@Test
public void throwsExceptionWithSpecificType() {
expectedException.expect(NullPointerException.class);
throw new NullPointerException();
}
@Test
public void throwsExceptionWithSpecificTypeAndMessage() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Wanted a donut.");
throw new IllegalArgumentException("Wanted a donut.");
}
}
在 JUnit5 中测试异常
要在 JUnit 5 中实现相同的功能,请使用全新的机制 :
测试方法
public class Calculator {
public double divide(double a, double b) {
if (b == 0.0) {
throw new IllegalArgumentException("Divider must not be 0");
}
return a/b;
}
}
该测试方法
public class CalculatorTest {
@Test
void triangularMinus5() { // The test method does not have to be public in JUnit5
Calculator calc = new Calculator();
IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> calculator.divide(42.0, 0.0));
// If the exception has not been thrown, the above test has failed.
// And now you may further inspect the returned exception...
// ...e.g. like this:
assertEquals("Divider must not be 0", thrown.getMessage());
}