JUnit5, AssertJ에서 Exception 테스트 코드 작성. How to test Exception in JUnit5, AssertJ
🎩

JUnit5, AssertJ에서 Exception 테스트 코드 작성. How to test Exception in JUnit5, AssertJ

Created
2022/07/10
Tags
TestCode
JUnit5
 
2022-07-05 @이영훈
 
JUnit5 (또는 AssertionJ)에서 Exception을 테스트하는 방법을 기록으로 남깁니다.
 
JUnit5로 테스트하는 방법과 AssertJ로 테스트하는 방법이 있습니다.
저는 JUnit5보다 AssertJ 라이브러리를 이용해서 Exception 테스트를 많이 합니다.
  • assertThatThrownBy 라는 함수명이 직관적이고
  • 테스트할 내용을 chaining 방식으로 표현할 수 있어 가독성이 좋습니다.
 
아래 두 방법을 직접 비교하면서 보고 편하신 것을 사용하면 될 거 같습니다.
 
 

AssertionJ의 assertThatThrownBy

[예시1]
Kotlin
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test

@Test
fun `test exception1 - AssertionJ`() {
    assertThatThrownBy {
				// lambda 부분입니다. 실행할 코드를 작성합니다.
        val list = listOf(1, 2, 3, 4)
        list.get(100)
    }
        .isExactlyInstanceOf(ArrayIndexOutOfBoundsException::class.java)
        .isInstanceOf(Exception::class.java)  // 부모 클래스 타입도 체크할 수 있습니다.
        .hasMessage("Index 100 out of bounds for length 4")
}
 
[예시2]
Kotlin
@Test
fun `test exception2 - AssertionJ`() {
    assertThatThrownBy { throw RuntimeException("Occurred run time exception") }
        .isExactlyInstanceOf(RuntimeException::class.java)
        .isInstanceOf(Exception::class.java)  // 부모 클래스 타입도 체크할 수 있습니다.
        .hasMessage("Occurred run time exception")
}
 
 

JUnit5의 assertThrows

[예시1]
Kotlin
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.assertThrows

@Test
fun `test exception1 - JUnit5`() {
    val assertion = assertThrows<ArrayIndexOutOfBoundsException> {
				// lambda 부분입니다. 실행할 코드를 작성합니다.
        val list = listOf(1, 2, 3, 4)
        list.get(100)
    }
    assertEquals("Index 100 out of bounds for length 4", assertion.message)
}
 
[예시2]
Kotlin
@Test
fun `test exception2 - JUnit5`() {
    val assertion = assertThrows<RuntimeException> { throw RuntimeException("Occurred run time exception") }
    assertEquals("Occurred run time exception", assertion.message)
}