>Java >java지도 시간 >JUnit 테스트에서 예외 처리를 어떻게 주장합니까?

JUnit 테스트에서 예외 처리를 어떻게 주장합니까?

Susan Sarandon
Susan Sarandon원래의
2025-01-04 07:54:35518검색

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();
}

JUnit <= 4.12

JUnit 버전 이하 4.12에서는 Rule 또는 TryCatch를 사용하여 예외를 처리할 수 있습니다.

Rule 사용:

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

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

TryCatch 사용:

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 테스트에서 예외 처리를 어떻게 주장합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.