JAVA/JUnit

[JUnit5] 테스트 작성(7) - 반복 테스트 (@RepeatedTest)

Jupiter는 @RepeatedTest를 통해 원하는 만큼 테스트를 반복하는 기능을 제공합니다. 반복되는 각 테스트들은 

@Test와 같이 작동합니다.

@RepeatedTest(10)
@Test
void repeatTest1(){
    System.out.println("test");
}

 

이 반복 테스트에 시너지를 내 줄 몇몇 @RepeatedTest 속성들이 있습니다.

name 속성

기본적으로 JUnit에서는 반복 시 해당 테스트가 몇 번째 테스트인지와 같은 기본적인 정보를 시각적으로 제공합니다.

만약 이를 다르게 표기하고 싶다면, name 속성에 파라미터들을 동적으로 입력하시면 됩니다. 다른 동적 파라미터들과 같이 중괄호('{ }') 안에 입력하시면 됩니다.

 

반복 횟수와 같은 정보들은 RepeatedTest의 정보를 가지는 RepeatedInfo를 통해 가져와야 합니다.

public class RepeatedNamingTest {

    // BeforeEach를 통해 정보를 미리 가져와야 함.
    @BeforeEach
    void init(TestInfo testInfo, RepetitionInfo repetitionInfo) {
        String displayName = testInfo.getTestMethod().get().getName();
        int totalRepetitions = repetitionInfo.getTotalRepetitions();
        int currentRepetition = repetitionInfo.getCurrentRepetition();
    }

    @RepeatedTest(10)	// 출력 형식 : repetition currentRepetition of 10
    void test1() {
        System.out.println("test");
    }

    @RepeatedTest(5)    // 출력 형식 : repetition currentRepetition of 5
    void test2(RepetitionInfo repetitionInfo) {
        assertEquals(5, repetitionInfo.getTotalRepetitions());
    }
 
    @DisplayName("반복 테스트")  // 출력 형식 : 반복테스트 currentRepetition / 5
    @RepeatedTest(value = 5, name = "{displayName} {currentRepetition}/{totalRepetitions}")
    void test3(TestInfo testInfo) {
        System.out.println("test");
    }
    
    @DisplayName("반복 테스트 2") // 출력 형식 : 반복테스트 :: currentRepetition / 5
    @RepeatedTest(value = 5, name = RepeatedTest.LONG_DISPLAY_NAME)
    void test4() {
        System.out.println("test");
    }
}

보통 이런 식으로 입력을 많이 합니다.

동적 파라미터 설명
{displayName} 메서드의 표시 이름
{currentRepetition} 현재 반복 회수
{totalRepetitions} 총 반복 회수

RepeatedTest 내장 표현방식들도 있으니 비슷한 표현방식이라면 이들을 이용하는 것이 생산성이 더욱 높아질 것입니다.

RepeatedTest 내장 표현 방식 표현 방식
LONG_DISPLAY_NAME Display name :: repetition currentRepetition of totalRepetitions
CURRENT_REPETITION_PLACEHOLDER currentRepetition만 표시
DISPLAY_NAME_PLACEHOLDER DisplayName만 표시
SHORT_DISPLAY_NAME 디폴트값
TOTAL_REPETITIONS_PLACEHOLDER totalRepetitions만 표시

 

기본적인 테스트를 넘어 반복 중 내부 파라미터까지 변경하고 싶다면 다음 포스트를 확인하시기 바랍니다.