捕獲預期的異常

可以在沒有任何 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());
}