포스트

Spring Boot Test - JUnit5 Assertions

몇 가지 assertions 기록


expected : 기대 값
actual : 실제 발생 한 값


assertAll(executables)

여러 검증을 한 번에 실행.
그룹 내에서 한 개 이상의 검증이 실패하면 테스트는 실패.
앞선 검증이 실패하더라도 뒤에 위치한 검증이 실행된다.


assertThrows(Class<T> expectedType, Executable executable)

기대한 예외가 발생하면 통과
기대한 예외의 하위 클래스가 발생해도 통과한다.


assertThrowsExactly(Class<T> expectedType, Executable executable)

기대한 예외가 발생하면 통과
정확히 기대한 예외가 발생해야 통과한다.
기대한 예외의 하위 클래스가 발생할 경우 실패


assertEquals(expected, actual)

두 값이 같으면 통과

객체인 경우 동일성 비교


동등성 비교

assertThat(Object actual).usingRecursiveComparision().isEqualTo(Object expected);

두 객체의 필드 값이 같으면 통과

org.assertj.core.api.Assertions.assertThat 제공

ex.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import static org.assertj.core.api.Assertions.assertThat;  
import static org.junit.jupiter.api.Assertions.*;

class EqualsTest {

    @Test 
    void test() {
        TestResponse one = new TestResponse("one", 1);  
        TestResponse oneSame = new TestResponse("one", 1);  
    	  
        assertAll(  
            () -> assertEquals(oneSame, one), // 실패
            () -> assertThat(oneSame).usingRecursiveComparison().isEqualTo(one) // 성공
        );
    }
    
    
    class TestResponse {  
        public String message;  
        public int num;  
          
        public TestResponse(String message, int num) {  
            this.message = message;  
            this.num = num;  
        }  
    }
}


assertNotEquals(unexpected, actual)

두 값이 다르면 통과


assertArrayEquals(expected, actual)

두 배열이 동일하면 통과


assertIterableEquals(Iterable<?> expected, Iterable<?> actual)

두 Iterable 객체가 동일하면 통과


assertLinesMatch(List<String> expectedLines, List<String> actualLines)

문자열 리스트가 동일하면 통과


assertTrue(condition)

조건이 참이면 통과


assertFalse(condition)

조건이 거짓인 경우 통과


assertNull(object)

객체가 null 이면 통과


assertNotNull(object)

객체가 null이 아니면 통과


assertTimeout(Duration timeout, Executable executable)

실행 가능한 코드가 지정된 시간 내에 완료되면 통과
만약 테스트를 실패해도 코드는 중단되지 않고 끝까지 실행 된다.


assertTimeoutPreemptively(Duration timeout, Executable executable)

실행 가능한 코드가 지정된 시간을 초과하면 통과
만약 테스트를 실패하면 코드도 중단된다.




Jupiter Assertions Document https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/Assertions.html

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.