Program Tip

junit 테스트 클래스에서 Spring 애플리케이션 컨텍스트 재사용

programtip 2020. 10. 24. 11:40
반응형

junit 테스트 클래스에서 Spring 애플리케이션 컨텍스트 재사용


많은 JUnit 테스트 케이스 (통합 테스트)가 있으며 논리적으로 서로 다른 테스트 클래스로 그룹화됩니다.

http://static.springsource.org/spring/docs/current/spring-framework-reference에 언급 된대로 테스트 클래스 당 한 번 Spring 애플리케이션 컨텍스트를로드하고 JUnit 테스트 클래스의 모든 테스트 케이스에 재사용 할 수 있습니다 . /html/testing.html

그러나 우리는 JUnit 테스트 클래스 묶음에 대해 Spring 애플리케이션 컨텍스트를 한 번만로드하는 방법이 있는지 궁금했습니다.

FWIW에서는 Spring 3.0.5, JUnit 4.5를 사용하고 Maven을 사용하여 프로젝트를 빌드합니다.


예, 이것은 완벽하게 가능합니다. locations테스트 클래스에서 동일한 속성 을 사용하기 만하면됩니다.

@ContextConfiguration(locations = "classpath:test-context.xml")

Spring은 locations속성 별로 애플리케이션 컨텍스트를 캐시 하므로 locations동일한 컨텍스트가 두 번째로 나타나면 Spring은 새 컨텍스트를 생성하는 대신 동일한 컨텍스트를 사용합니다.

이 기능에 대한 기사를 작성했습니다 : Speeding up Spring integration tests . 또한 Spring 문서에서 자세히 설명합니다 : 9.3.2.1 컨텍스트 관리 및 캐싱 .

이것은 흥미로운 의미를 가지고 있습니다. Spring은 JUnit이 언제 완료되었는지 알지 못하기 때문에 모든 컨텍스트를 영원히 캐시하고 JVM 종료 후크를 사용하여 닫습니다. 이 동작 (특히 다른 테스트 클래스가 많은 경우 locations)은 과도한 메모리 사용, 메모리 누수 등을 유발할 수 있습니다. 컨텍스트 캐싱의 또 다른 이점입니다.


Tomasz Nurkiewicz의 답변에 추가하기 위해 Spring 3.2.2부터 @ContextHierarchy주석을 사용하여 별도의 연관된 다중 컨텍스트 구조를 가질 수 있습니다. 이는 여러 테스트 클래스가 메모리 내 데이터베이스 설정 (예 : 데이터 소스, EntityManagerFactory, tx 관리자 등)을 공유하려는 경우에 유용합니다.

예를 들면 :

@ContextHierarchy({
  @ContextConfiguration("/test-db-setup-context.xml"),
  @ContextConfiguration("FirstTest-context.xml")
})
@RunWith(SpringJUnit4ClassRunner.class)
public class FirstTest {
 ...
}

@ContextHierarchy({
  @ContextConfiguration("/test-db-setup-context.xml"),
  @ContextConfiguration("SecondTest-context.xml")
})
@RunWith(SpringJUnit4ClassRunner.class)
public class SecondTest {
 ...
}

이 설정을 통해 "test-db-setup-context.xml"을 사용하는 컨텍스트는 한 번만 생성되지만 그 안의 빈은 개별 단위 테스트의 컨텍스트에 주입 될 수 있습니다.

매뉴얼에 대한 추가 정보 : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-ctx-management ( " context hierarchy " 검색 )

참고 URL : https://stackoverflow.com/questions/8501975/reuse-spring-application-context-across-junit-test-classes

반응형