자동 구성은 사용자 구성 ( @Bean 정의 및 Environment 사용자 정의), 상태 평가 (특정 라이브러리의 존재) 및 기타 여러 요소에 의해 영향을받을 수 있다. 구체적으로 각 테스트는 그 커스텀한 조합들을 나타내는 잘 정의 된 ApplicationContext 을 만들어야한다 .ApplicationContextRunner 는 그것을 성취 할 수있는 좋은 방법을 제공다.
ApplicationContextRunner는 일반적으로 기본 구성을 수집하는 테스트 클래스의 필드로 정의된다. 다음 예제는 UserServiceAutoConfiguration가 항상 호출 되는지 확인한다.
ApplicationContextRunner 는 특정 설정을 가져와서 테스팅할 수 있도록 도와준다.
아래 예제같은 경우에는 UserServiceAutoConfiguration 설정을 가져와서 테스팅할 수 있도록 한다!
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(UserServiceAutoConfiguration.class));
여러 자동 구성을 정의해야하는 경우 응용 프로그램을 실행하는 순서와 완전히 동일한 순서로 선언을 정렬 할 필요가 없다.
각 테스트는 Runner를 사용하여 특정 유스 케이스를 나타낼 수 있다. 예를 들어, 아래 샘플에서는 사용자 구성 ( UserConfiguration)을 호출 하고 자동 구성이 올바르게 작동하는지 확인합니다. run 메소드 실행은 Assert4J에서 사용할 수있는 콜백 컨텍스트(인자값 context)를 제공합니다.
@Test
public void defaultServiceBacksOff() {
this.contextRunner.withUserConfiguration(UserConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(UserService.class);
assertThat(context.getBean(UserService.class))
.isSameAs(context.getBean(UserConfiguration.class).myUserService());
});
}
@Configuration
static class UserConfiguration {
@Bean
public UserService myUserService() {
return new UserService("mine");
}
}
assertThat().isSameAs : 실제 값이 주어진 것과 같인지 == 비교를 통해서 검증한다. 위의 예제에서는 context에서 UserService 빈을 가져와서 UserConfiguration 에 있는 UserService 빈이랑 같은지 비교한다는 의미!
configuration에서 빈 가져와서 비교하는 부분이 빈 이름만으로 확인하도록 바꼈어!! 원래 == 이거가 주소값(해시?) 를 비교하는 거잖아? 그걸 빈 이름으로 비교해도 된다는 이야기인듯!
Runner 는 ConditionEvaluationReport 를 표시하는 데 사용할 수도 있다. report는 INFO 또는 DEBUG level 에서 출력할 수 있습니다 . 다음 예는 ConditionEvaluationReportLoggingListener 을 사용하여 자동 구성 테스트에서 report를 출력하는 방법을 보여준다.
@Test
public void autoConfigTest {
ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener(
LogLevel.INFO);
ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withInitializer(initializer).run((context) -> {
// Do something...
});
}
49.4.1 web context 시뮬레이션
Servlet 또는 Reactive 웹 응용 프로그램 컨텍스트에서만 작동하는 자동 구성을 테스트해야하는 경우 WebApplicationContextRunner 또는 ReactiveWebApplicationContextRunner를 각각 사용하십시오.
49.4.2 클래스패스 오버라이딩
특정 클래스나 패키지가 런타임에 존재하지 않을 때 어떤 일이 발생하는지 테스트 할 수도 있다. 스프링 부트에는 Runner에 의해 쉽게 사용될 수 있는 FilteredClassLoader 가 들어있다. 다음 예에서는 UserService가 없을 때 자동 구성이 적절히 해제되어 있다고 가정한다.