首頁 >Java >java教程 >如何在 JUnit 測試中斷言異常處理?

如何在 JUnit 測試中斷言異常處理?

Susan Sarandon
Susan Sarandon原創
2025-01-04 07:54:35524瀏覽

How Do I Assert Exception Handling in JUnit Tests?

在 JUnit 測試中斷言異常處理

在 JUnit 中,測試應拋出異常的程式碼需要乾淨簡潔的方法。雖然可以手動檢查異常,但這不是慣用的方式。

JUnit 5 和 4.13

在 JUnit 版本 5 和 4.13 中,您可以使用 @Test(expected = ExceptionClass.class) 註解關於測試方法。這期望拋出指定的異常。

範例:

@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
    ArrayList emptyList = new ArrayList();
    emptyList.get(0);
}

AssertJ 和 Google-Truth

如果使用 AssertJ 或 Google-Truth等等庫,您可以使用他們的斷言需要驗證

AssertJ:

import static org.assertj.core.api.Assertions.assertThatThrownBy;

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    assertThatThrownBy(() -> foo.doStuff()).isInstanceOf(IndexOutOfBoundsException.class);
}

Google-Truth:

import static com.google.common.truth.Truth.assertThat;

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    assertThat(assertThrows(IndexOutOfBoundsException.class, foo::doStuff)).isNotNull();
}

Google-Truth:

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void testIndexOutOfBoundsException() {
    thrown.expect(IndexOutOfBoundsException.class);
    ArrayList emptyList = new ArrayList();
    emptyList.get(0);
}

import static org.junit.Assert.assertEquals;

@Test
public void testIndexOutOfBoundsException() {
    try {
        ArrayList emptyList = new ArrayList();
        emptyList.get(0);
        fail("IndexOutOfBoundsException was expected");
    } catch (IndexOutOfBoundsException e) {
        assertEquals(e.getClass(), IndexOutOfBoundsException.class);
    }
}
JUnit 在JUnit 版本小於或等於4.12,可以使用Rule或TryCatch來處理異常。 使用Rule:使用TryCatch:

以上是如何在 JUnit 測試中斷言異常處理?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn