Loading...
Spring Framework Reference Documentation 7.0.2의 Context Caching의 한국어 번역본입니다.
아래의 경우에 피드백에서 신고해주신다면 반영하겠습니다.
감사합니다 :)
일단 TestContext 프레임워크가 테스트를 위해 ApplicationContext (또는 WebApplicationContext)를
로드하면, 해당 컨텍스트는 캐시되고 동일한 테스트 스위트 내에서 동일한 고유 컨텍스트 설정을
선언하는 이후의 모든 테스트에 재사용됩니다. 캐싱이 어떻게 동작하는지 이해하려면, "고유"와
"테스트 스위트"가 의미하는 바를 이해하는 것이 중요합니다.
ApplicationContext는 이를 로드하는 데 사용되는 설정 매개변수의 조합에 의해
고유하게 식별될 수 있습니다. 따라서 설정 매개변수의 고유 조합이 컨텍스트가 캐시되는
키를 생성하는 데 사용됩니다.
TestContext 프레임워크는 컨텍스트 캐시 키를 구성하기 위해 다음과 같은 설정 매개변수를 사용합니다:
locations (@ContextConfiguration에서)classes (@ContextConfiguration에서)contextInitializerClasses (@ContextConfiguration에서)contextCustomizers (ContextCustomizerFactory에서) – 여기에는
@DynamicPropertySource 메서드, 빈 오버라이드 (@TestBean, @MockitoBean,
@MockitoSpyBean 등)뿐만 아니라 Spring Boot의 테스트 지원에서 제공하는 다양한 기능이
포함됩니다.contextLoader (@ContextConfiguration에서)parent (@ContextHierarchy에서)activeProfiles (@ActiveProfiles에서)propertySourceDescriptors (@TestPropertySource에서)propertySourceProperties (@TestPropertySource에서)resourceBasePath (@WebAppConfiguration에서)예를 들어, TestClassA가 @ContextConfiguration의 locations (또는 value) attribute에 대해
{"app-config.xml", "test-config.xml"}를 지정하면, TestContext 프레임워크는 해당하는
ApplicationContext를 로드하고 오직 그 location에만 기반한 키 아래 static 컨텍스트 캐시에
저장합니다.
따라서 TestClassB도 locations에 대해 (명시적으로 또는 상속을 통해 암시적으로)
{"app-config.xml", "test-config.xml"}를 정의하지만 @WebAppConfiguration, 다른
ContextLoader, 다른 활성 프로필, 다른 컨텍스트 이니셜라이저, 다른 컨텍스트 커스터마이저, 다른
테스트 또는 동적 프로퍼티 소스, 또는 다른 부모 컨텍스트를 정의하지 않는다면, 동일한
ApplicationContext가 두 테스트 클래스 간에 공유됩니다. 이는 애플리케이션 컨텍스트를 로드하는 설정
비용이 (테스트 스위트당) 한 번만 발생하고 이후의 테스트 실행은 훨씬 더 빨라진다는 것을 의미합니다.
Test suites and forked processes The Spring TestContext framework stores application contexts in a static cache. This means that the context is literally stored in a
staticvariable. In other words, if tests run in separate processes, the static cache is cleared between each test execution, which effectively disables the caching mechanism. To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE. Similarly, when executing tests with a build framework such as Ant, Maven, or Gradle, it is important to make sure that the build framework does not fork between tests. For example, if theforkModefor the Maven Surefire plug-in is set toalwaysorpertest, the TestContext framework cannot cache application contexts between test classes, and the build process runs significantly more slowly as a result.
컨텍스트 캐시의 크기는 기본 최대 크기 32로 제한됩니다. 최대 크기에 도달하면, 가장 최근에 사용되지 않은 (LRU) 제거 정책이 사용되어 오래된 컨텍스트를 제거하고 종료합니다.
JVM 시스템 프로퍼티
spring.test.context.cache.maxSize를 설정하여 커맨드 라인 또는 빌드 스크립트에서 최대 크기를
구성할 수 있습니다. 대안으로,
SpringProperties 메커니즘을 통해 동일한 프로퍼티를 설정할 수 있습니다.
Spring Framework 7.0부터, 컨텍스트 캐시에 저장된 애플리케이션 컨텍스트는 더 이상 적극적으로 사용되지 않을 때 paused 되며, 캐시에서 컨텍스트가 다음에 다시 조회될 때 자동으로 restarted 됩니다. 구체적으로, 후자는 애플리케이션 컨텍스트의 모든 자동 시작 빈을 다시 시작하여 라이프사이클 상태를 효과적으로 복원합니다.
이는 컨텍스트가 테스트에 의해 사용되지 않는 동안 컨텍스트 내의 백그라운드
프로세스가 적극적으로 실행되지 않도록 보장합니다. 예를 들어, JMS 리스너 컨테이너, 스케줄된 작업,
그리고 컨텍스트에서 Lifecycle 또는 SmartLifecycle을 구현하는 기타 컴포넌트는 컨텍스트가 테스트에
의해 다시 사용될 때까지 "stopped" 상태에 있게 됩니다. 그러나 SmartLifecycle 컴포넌트는
SmartLifecycle#isPauseable()에서 false를 반환함으로써 일시 중지에서 제외될 수 있습니다.
주어진 테스트 스위트 내에서 많은 수의 애플리케이션 컨텍스트가 로드되면 스위트가 불필요하게 오랜 시간이 걸릴 수 있으므로, 로드되고 캐시된 컨텍스트의 정확한 수를 아는 것이 종종 유익합니다.
기본 컨텍스트
캐시에 대한 통계를 보려면 org.springframework.test.context.cache 로깅 카테고리의 로그 레벨을
DEBUG로 설정하면 됩니다.
테스트가 애플리케이션 컨텍스트를 손상시키고 (예를 들어, 빈 정의나 애플리케이션 객체의
상태를 수정함으로써) 다시 로드해야 하는 드문 경우에는, 테스트 클래스나 테스트 메서드에
@DirtiesContext를 어노테이션으로 지정할 수 있습니다 ( @DirtiesContext에 대한 논의는
Spring Testing Annotations를 참조하십시오).
이는 Spring에게 캐시에서 컨텍스트를 제거하고 동일한 애플리케이션 컨텍스트를 필요로 하는 다음 테스트를
실행하기 전에 애플리케이션 컨텍스트를 재구축하도록 지시합니다. @DirtiesContext 어노테이션에 대한
지원은 DirtiesContextBeforeModesTestExecutionListener와
DirtiesContextTestExecutionListener에 의해 제공되며, 이들은 기본적으로 활성화되어 있다는 점에
유의하십시오.
ApplicationContext lifecycle and console logging When you need to debug a test executed with the Spring TestContext Framework, it can be useful to analyze the console output (that is, output to the
SYSOUTandSYSERRstreams). Some build tools and IDEs are able to associate console output with a given test; however, some console output cannot be easily associated with a given test. With regard to console logging triggered by the Spring Framework itself or by components registered in theApplicationContext, it is important to understand the lifecycle of anApplicationContextthat has been loaded by the Spring TestContext Framework within a test suite. TheApplicationContextfor a test is typically loaded when an instance of the 테스트 클래스 is being prepared — for example, to perform dependency injection into@Autowired필드 of the 테스트 인스턴스. This means that any console logging triggered during the initialization of theApplicationContexttypically cannot be associated with an individual 테스트 메서드. However, if the 컨텍스트 is closed immediately before the execution of a 테스트 메서드 according to@DirtiesContextsemantics, a new 인스턴스 of the 컨텍스트 will be loaded just prior to execution of the 테스트 메서드. In the latter scenario, an IDE or build tool may potentially associate console logging with the individual 테스트 메서드. TheApplicationContextfor a 테스트 can be closed via one of the following 시나리오.
- The 컨텍스트 is closed according to
@DirtiesContextsemantics.- The 컨텍스트 is closed because it has been automatically evicted from the 캐시 according to the LRU 제거 정책.
- The 컨텍스트 is closed via a JVM 종료 훅 when the JVM for the 테스트 스위트 terminates. If the 컨텍스트 is closed according to
@DirtiesContextsemantics after a particular 테스트 메서드, an IDE or build tool may potentially associate console logging with the individual 테스트 메서드. If the 컨텍스트 is closed according to@DirtiesContextsemantics after a 테스트 클래스, any console logging triggered during the shutdown of theApplicationContextcannot be associated with an individual 테스트 메서드. Similarly, any console logging triggered during the shutdown phase via a JVM 종료 훅 cannot be associated with an individual 테스트 메서드. When a SpringApplicationContextis closed via a JVM 종료 훅, callbacks executed during the shutdown phase are executed on a thread namedSpringContextShutdownHook. So, if you wish to disable console logging triggered when theApplicationContextis closed via a JVM 종료 훅, you may be able to register a custom 필터 with your 로깅 프레임워크 that allows you to ignore any 로깅 initiated by that thread.
Working with Web Mocks
Context Failure Threshold