Java/Java 학습

[JAVA] 예외 테스트 (jUnit5의 assertThrows)

HSY_mumu 2022. 4. 28. 14:00
728x90

1. 예외 발생 메서드(검증 대상)

public class DoSomething {
    public static void func() {
        throw new RuntimeException("some exception message...");
    }
}

RuntimeException이 발생하는 메서드를 만들었다. 우리가 검증해야할 검증 대상이다.

2. 예외 테스트 코드 작성하기

위에서 작성한 "예외 발생 메서드가 예외를 잘 발생하는지"를 테스하는 코드를 4가지 방법으로 작성해볼 수 있다.

 

방법1. assertThrows: 예외 타입이 같은지 검사

import static org.junit.jupiter.api.Assertions.assertThrows;
 
@Test
public void junit5에서_exception_테스트_1() {
    Assertions.assertThrows(RuntimeException.class, () -> {
        DoSomething.func();
    });
}

Assertions.assertThrows의 두 번째 인자인 DoSomething.func()를 실행하여 첫 번째 인자인 예외 타입과 같은지(혹은 캐스팅이 가능한 상속 관계의 예외인지) 검사합니다.

assertThrows(Class<> classType, Executable executable)

executbale을 실행하여 예외가 발생할 경우, classType과 앞에서 발생한 exception이 같은 타입인지 비교

  • 첫번째 인자: 발생할 예외 클래스의 Class 타입

방법 2. 예외 메시지 테스트 - assertEquals (try ~ catch): 예외 메시지가 같은지 검사

import static org.junit.jupiter.api.Assertions.assertThrows;
 
@Test
public void junit5에서_exception_테스트_3() {
    try {
        DoSomething.func();
    } catch (RuntimeException e) {
        assertThat(e.getMessage()).isEqualTo("some exception message...");
    }
}

방법 3. 예외 메시지 테스트 - assertThrows 반환값 사용: 예외 메시지가 같은지 검사

@Test
public void junit5에서_exception_테스트_4() {
    Throwable exception = assertThrows(RuntimeException.class, () -> {
        DoSomething.func();
    });
    assertThat(exception.getMessage()).isEqualTo("some exception message...");
}

 

[참고] https://covenant.tistory.com/256

 

완벽정리! Junit5로 예외 테스트하는 방법

환경 구성 testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeClasspath - Runtime classpath of source set 'test'. +--- org.springframework.boot:spring-boot-starter-web..

covenant.tistory.com

 

728x90