Spring

ContextConfiguration이란?

dev_SiWoo 2022. 1. 19. 10:28

@ContextConfiguration는 테스트 실행 시 사용할 Spring Context(ApplicationContext)를 어떻게 구성할지

설정하는 어노테이션이다.

 

보통  통합테스트 환경에서 ApplicationContext를 어떻게 로드하고 설정할지 결정하는데 사용되는

클래스 레벨의 어노테이션이다.

 

주로 테스트 환경에서 @SpringBootTest를 이용해 전체 빈을 로딩하는 대신 가벼운 Context 환경을 위해 사용된다.

 

테스트가 시작되면 스프링이 테스트 전용 ApplicationContext를 만들고, 지정한 설정(XML, @Configuration, @ComponentScan 등)을 기반으로 Bean을 로딩한다.

 

@ContextConfiguration(locations = {"file:Deployed Resources/webapp/WEB-INF/spring/**/*.xml"})
public class SomeTest {
    // Spring Context가 로딩된 상태에서 테스트 실행
}

 

  • locations: XML 설정 파일 경로(패턴 사용 가능)
  • 또는 classes: 자바 기반 설정 클래스(@Configuration) 지정
  • 역할: IoC 컨테이너(Sprint Context)를 테스트 시점에 부팅해 Bean 주입/트랜잭션/프로퍼티 등을 테스트에서 그대로 활용

 

따라서 @ContextConfiguration를 사용하는 코드를 src/test/java에 위치해야하는 것이다.

 

 

권장 의존성 설정 (Maven/Gradle) 방법

 

(1) SpringBoot 사용시 

 

▶  Maven

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

 

▶  Gradle

testImplementation("org.springframework.boot:spring-boot-starter-test")

 

 

(2) 순수 Spring

 

▶  Maven

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${spring.version}</version>
  <scope>test</scope>
</dependency>

 

 

▶  Gradle

testImplementation("org.springframework:spring-test:${springVersion}")