Programming/Java

[JAVA][JUnit]자주 사용하는 Annotation

베나코드 2022. 3. 4. 22:42

1. @Test

-. 아래는 JUnit User Guide에 나오는 test case

-. 메소드가 테스트 메소드임을 나타낸다.

import static org.junit.jupiter.api.Assertions.assertEquals;
import example.util.Calculator;
import org.junit.jupiter.api.Test;

class MyFirstJUnitJupiterTests {
    private final Calculator calculator = new Calculator();

    @Test
    void addition() {
        assertEquals(2, calculator.add(1, 1));
    }
}

2. @DisplayName

-. test 메소드의 출력을 원하는 대로 설정할 수 있다.(=사용자 지정 표시 이름)

-. 아래 메소드는 기본적으로 "addition"으로 출력되겠지만,

-. @DisplayName으로 설정한 이름 "더하기 테스트"로 출력된다.

    @Test
    @DisplayName("더하기 테스트")
    void addition() {
        assertEquals(2, calculator.add(1, 1));
    }

 

3. @DisplayNameGeneration

-. 테스트 클래스에 대한 사용자 지정 표시 이름 생성기를 선언합니다.

-. 해당 클래스 내의 Test 메소드의 이름을 원하는대로 생성한다.

class DisplayNameGeneratorDemo {

    @Nested
    @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
    class A_year_is_not_supported {

        @Test
        void if_it_is_zero() {
        }

        @DisplayName("A negative value for year is not supported by the leap year computation.")
        @ParameterizedTest(name = "For example, year {0} is not supported.")
        @ValueSource(ints = { -1, -4 })
        void if_it_is_negative(int year) {
        }

    }

    @Nested
    @IndicativeSentencesGeneration(separator = " -> ", generator = DisplayNameGenerator.ReplaceUnderscores.class)
    class A_year_is_a_leap_year {

        @Test
        void if_it_is_divisible_by_4_but_not_by_100() {
        }

        @ParameterizedTest(name = "Year {0} is a leap year.")
        @ValueSource(ints = { 2016, 2020, 2048 })
        void if_it_is_one_of_the_following_years(int year) {
        }

    }

}

-. 위 예시 코드 출력 결과 :

+-- DisplayNameGeneratorDemo [OK]
  +-- A year is not supported [OK]
  | +-- A negative value for year is not supported by the leap year computation. [OK]
  | | +-- For example, year -1 is not supported. [OK]
  | | '-- For example, year -4 is not supported. [OK]
  | '-- if it is zero() [OK]
  '-- A year is a leap year [OK]
    +-- A year is a leap year -> if it is divisible by 4 but not by 100. [OK]
    '-- A year is a leap year -> if it is one of the following years. [OK]
      +-- Year 2016 is a leap year. [OK]
      +-- Year 2020 is a leap year. [OK]
      '-- Year 2048 is a leap year. [OK]

-. DisplayNameGenerator.ReplaceUnderscores.class를 이용하여 unerscore(=우리가 흔히 말하는 언더바)를 제거하여 출력된 것을 확인할 수 있다. 두번째 클래스에서는 seperator로 "->" 사용했다.

4. @Nested

-. 위 코드에서도 볼 수 있듯이, 비슷한 테스트별로 묶을 때 사용한다.

-. 한 기능의 단위테스트에 대해 true, false, exception을 묶는다거나 할 때 활용할 수 있다.

5. @ParameterizedTest

-. 매개변수가 있는 Test메소드임을 나타낸다.

-. 출력문을 매개변수를 포함하여 나타낼 수 있다.

-. 위의 코드에서 @ParameterizedTest(name = "Year {0} is a leap year.") 로 작성하였기 때문에,

-. 2016이란 변수값이 들어왔을 때, Year 2016 is a leap year. [OK] 로 출력했다.

6. @BeforeAll

-. 테스트 클래스의 모든 @Test@RepeatedTest@ParameterizedTest@TestFactory method보다 먼저 실행된다.

-. 즉, 해당 클래스에서 거의 제일 먼저 실행된다.

-. JUnit4의 @BeforeClass와 유사하다.

7. @AfterAll

-. 정확히 @BeforAll과 반대로 실행되는 어노테이션

-. 해당 클래스의 모든 test가 끝나면 마지막에 실행된다.

-. JUnit4의 @AfterClass와 유사하다.

8. @BeforeEach

-. 현재 클래스의 각 @Test, @RepeatedTest, @ParameterizedTest, @TestFactory 메서드보다 먼저 실행된다.

-. 즉, 해당 클래스의 각각의 테스트메서드가 실행되기 전마다 한번씩 실행된다.

-.  보통 테스트에 사용되는 변수 초기화에 사용거나 테스트에 필요한 설정을 세팅할 때 사용된다.

-. JUnit4의 @Before와 유사하다.

9. @AfterEach

-. 정확히 @BeforeEach와 반대로 실행되는 어노테이션

-. 해당 클래스의 각 테스트 메서드가 실행된 후마다 한번씩 실행된다.

-. JUnit4의 @After와 유사하다.

 

--참고

https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

 

JUnit 5 User Guide

Although the JUnit Jupiter programming model and extension model will not support JUnit 4 features such as Rules and Runners natively, it is not expected that source code maintainers will need to update all of their existing tests, test extensions, and cus

junit.org