TIL

2024.06.18.화 테스트 어노테이션 정리

Nellucia 2024. 6. 19. 15:48

 

 

 

1. @SpringBootTest

 

전체 애플리케이션 컨텍스트를 로드.  단위 테스트를 할 때는 전체 컨텍스트를 로드하는 것 보단 필요한 컨텍스트만 로드하는 것이 좋다.

 

2. @WebMvcTest

 

웹 계층(컨트롤러)을 테스트하는 데 사용된다. 이 어노테이션을 사용하면 컨트롤러와 관련된 빈들만 로드된다.

 

3. @DataJpaTest

 

JPA 리포지토리를 테스트하는 데 사용된다. 이 어노테이션을 사용하면 JPA 관련 구성 요소만 로드되며, 인메모리 데이터베이스를 사용한다.

 

4.@TestConfiguration

 

테스트에 특화된 구성 클래스를 정의할 때 사용한다. 이를 통해 특정 빈을 재정의하거나 추가할 수 있다.

 

ex)

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

@TestConfiguration
public class MyTestConfig {

    @Bean
    @Primary
    public MyService myService() {
        return new MyMockService();
    }
}

@SpringBootTest
@Import(MyTestConfig.class)
public class MyServiceTests {

    @Autowired
    private MyService myService;

    @Test
    public void testServiceMethod() {
        // Use the MyMockService for testing
        String result = myService.someMethod();
        assertThat(result).isEqualTo("Mock result");
    }
}

 

 

5.@ContextConfiguration

 

특정 컨텍스트 설정을 명시적으로 정의하여 로드할 때 사용한다.

import org.junit.jupiter.api.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@SpringJUnitConfig
@ContextConfiguration(classes = MyTestConfig.class)
public class MyServiceTests {

    @Autowired
    private MyService myService;

    @Test
    public void testServiceMethod() {
        String result = myService.someMethod();
        assertThat(result).isEqualTo("Expected result");
    }
}

 

6.@SpringJUnitConfig

JUnit 5와 Spring TestContext Framework를 통합하기 위한 어노테이션.

이 어노테이션은 @ExtendWith(SpringExtension.class)와 @ContextConfiguration을 결합하여 Spring 컨텍스트를 쉽게 설정하고 테스트할 수 있도록 도와준다. 주로 JUnit 5에서 사용된다.

 

7. @Nested

 

중첩 테스트 클래스를 정의하여 논리적으로 관련된 테스트를 그룹화한다.

 

@SpringBootTest
public class MyServiceTests {

    @Nested
    class WhenCreatingUser {
        @Test
        void testUserCreation() {
            // Test logic here
        }
    }

    @Nested
    class WhenDeletingUser {
        @Test
        void testUserDeletion() {
            // Test logic here
        }
    }
}

 

 

8. @RepeatedTest

 

JUnit 5에서 동일한 테스트를 여러 번 반복 실행한다.

 

@RepeatedTest(5)
public void repeatedTest(RepetitionInfo repetitionInfo) {
    System.out.println("Repetition " + repetitionInfo.getCurrentRepetition() + " of " + repetitionInfo.getTotalRepetitions());
    // Test logic here
}

 

 

9. @ParameterizedTest

 

JUnit 5에서 다양한 매개변수로 동일한 테스트를 실행한다.

@ParameterizedTest
@ValueSource(strings = {"Hello", "World"})
public void parameterizedTest(String word) {
    assertNotNull(word);
}

 

 

10. @BeforeAll 및 @AfterAll

 

JUnit 5에서 모든 테스트 메소드 실행 전후에 한 번 실행되는 메소드를 정의한다.

static으로 선언해야 하는데, @TestInstance를 사용해서 LifeCyle을 PER_CLASS로 선언하면 static을 쓰지 않아도 되긴하다.

@BeforeAll
public static void setUpBeforeAll() {
    // Initialization code here
}

@AfterAll
public static void tearDownAfterAll() {
    // Cleanup code here
}

 

 

11.@TestInstance

 

테스트 클래스의 인스턴스 생명주기를 제어하는 데 사용된다

. 기본적으로 JUnit은 각 테스트 메소드 실행 시마다 새로운 테스트 클래스 인스턴스를 생성하지만, @TestInstance를 사용하면 생명주기를 변경할 수 있다.

 

이 어노테이션은 두가지 생명주기 옵션을 제공한다.

 

1.@TestInstance(TestInstance.Lifecycle.PER_METHOD) (기본값)

 

- 각 테스트 메소드마다 새로운 테스트 클래스 인스턴스를 생성한다.

- 테스트 메소드 간의 상태 공유를 방지하는 데 유용

 

2.@TestInstance(TestInstance.Lifecycle.PER_CLASS)

 

- 테스트 클래스당 하나의 인스턴스만 생성하여 모든 테스트 메소드에서 동일한 인스턴스를 사용한다.

- 테스트 메소드 간에 상태를 공유해야 하거나, 테스트 클래스의 인스턴스 생성 비용이 높을 때 유용

- PER_CLASS를 사용할때는 테스트 메소드 간에 상태를 공유할 수 있지만, 테스트 간의 독립성을 저해시킬 수 있으므로 사용하는데 주의가 필요하다.