Polish output capture names

This commit is contained in:
Phillip Webb 2019-07-14 18:07:47 +01:00
parent cdf43a7489
commit c3816bfe7b
73 changed files with 328 additions and 335 deletions

View File

@ -124,23 +124,23 @@ class PrometheusMetricsExportAutoConfigurationTests {
} }
@Test @Test
void withPushGatewayEnabled(CapturedOutput capturedOutput) { void withPushGatewayEnabled(CapturedOutput output) {
this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class))
.withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true") .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true")
.withUserConfiguration(BaseConfiguration.class).run((context) -> { .withUserConfiguration(BaseConfiguration.class).run((context) -> {
assertThat(capturedOutput).doesNotContain("Invalid PushGateway base url"); assertThat(output).doesNotContain("Invalid PushGateway base url");
hasGatewayURL(context, "http://localhost:9091/metrics/job/"); hasGatewayURL(context, "http://localhost:9091/metrics/job/");
}); });
} }
@Test @Test
@Deprecated @Deprecated
void withCustomLegacyPushGatewayURL(CapturedOutput capturedOutput) { void withCustomLegacyPushGatewayURL(CapturedOutput output) {
this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class))
.withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true", .withPropertyValues("management.metrics.export.prometheus.pushgateway.enabled=true",
"management.metrics.export.prometheus.pushgateway.base-url=localhost:9090") "management.metrics.export.prometheus.pushgateway.base-url=localhost:9090")
.withUserConfiguration(BaseConfiguration.class).run((context) -> { .withUserConfiguration(BaseConfiguration.class).run((context) -> {
assertThat(capturedOutput).contains("Invalid PushGateway base url").contains("localhost:9090"); assertThat(output).contains("Invalid PushGateway base url").contains("localhost:9090");
hasGatewayURL(context, "http://localhost:9090/metrics/job/"); hasGatewayURL(context, "http://localhost:9090/metrics/job/");
}); });
} }

View File

@ -75,21 +75,21 @@ class RestTemplateMetricsConfigurationTests {
} }
@Test @Test
void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) {
this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(2); assertThat(registry.get("http.client.requests").meters()).hasSize(2);
assertThat(capturedOutput).contains("Reached the maximum number of URI tags for 'http.client.requests'.") assertThat(output).contains("Reached the maximum number of URI tags for 'http.client.requests'.")
.contains("Are you using 'uriVariables'?"); .contains("Are you using 'uriVariables'?");
}); });
} }
@Test @Test
void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) {
this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(3); assertThat(registry.get("http.client.requests").meters()).hasSize(3);
assertThat(capturedOutput) assertThat(output)
.doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.") .doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.")
.doesNotContain("Are you using 'uriVariables'?"); .doesNotContain("Are you using 'uriVariables'?");
}); });

View File

@ -74,21 +74,21 @@ class WebClientMetricsConfigurationTests {
} }
@Test @Test
void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) {
this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(2); assertThat(registry.get("http.client.requests").meters()).hasSize(2);
assertThat(capturedOutput).contains("Reached the maximum number of URI tags for 'http.client.requests'.") assertThat(output).contains("Reached the maximum number of URI tags for 'http.client.requests'.")
.contains("Are you using 'uriVariables'?"); .contains("Are you using 'uriVariables'?");
}); });
} }
@Test @Test
void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) {
this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(3); assertThat(registry.get("http.client.requests").meters()).hasSize(3);
assertThat(capturedOutput) assertThat(output)
.doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.") .doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.")
.doesNotContain("Are you using 'uriVariables'?"); .doesNotContain("Are you using 'uriVariables'?");
}); });

View File

@ -66,25 +66,24 @@ class WebFluxMetricsAutoConfigurationTests {
} }
@Test @Test
void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) {
this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class))
.withUserConfiguration(TestController.class) .withUserConfiguration(TestController.class)
.withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(2); assertThat(registry.get("http.server.requests").meters()).hasSize(2);
assertThat(capturedOutput) assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'");
.contains("Reached the maximum number of URI tags " + "for 'http.server.requests'");
}); });
} }
@Test @Test
void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) {
this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class))
.withUserConfiguration(TestController.class) .withUserConfiguration(TestController.class)
.withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(3); assertThat(registry.get("http.server.requests").meters()).hasSize(3);
assertThat(capturedOutput) assertThat(output)
.doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); .doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'");
}); });
} }

View File

@ -104,25 +104,24 @@ class WebMvcMetricsAutoConfigurationTests {
} }
@Test @Test
void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) { void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestController.class) this.contextRunner.withUserConfiguration(TestController.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class))
.withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(2); assertThat(registry.get("http.server.requests").meters()).hasSize(2);
assertThat(capturedOutput) assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'");
.contains("Reached the maximum number of URI tags " + "for 'http.server.requests'");
}); });
} }
@Test @Test
void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) { void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestController.class) this.contextRunner.withUserConfiguration(TestController.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, WebMvcAutoConfiguration.class))
.withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context); MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(3); assertThat(registry.get("http.server.requests").meters()).hasSize(3);
assertThat(capturedOutput) assertThat(output)
.doesNotContain("Reached the maximum number of URI tags " + "for 'http.server.requests'"); .doesNotContain("Reached the maximum number of URI tags " + "for 'http.server.requests'");
}); });
} }

View File

@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class ManagementContextAutoConfigurationTests { class ManagementContextAutoConfigurationTests {
@Test @Test
void childManagementContextShouldStartForEmbeddedServer(CapturedOutput capturedOutput) { void childManagementContextShouldStartForEmbeddedServer(CapturedOutput output) {
WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( WebApplicationContextRunner contextRunner = new WebApplicationContextRunner(
AnnotationConfigServletWebServerApplicationContext::new) AnnotationConfigServletWebServerApplicationContext::new)
.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class,
@ -51,7 +51,7 @@ class ManagementContextAutoConfigurationTests {
ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class,
EndpointAutoConfiguration.class)); EndpointAutoConfiguration.class));
contextRunner.withPropertyValues("server.port=0", "management.server.port=0") contextRunner.withPropertyValues("server.port=0", "management.server.port=0")
.run((context) -> assertThat(tomcatStartedOccurencesIn(capturedOutput)).isEqualTo(2)); .run((context) -> assertThat(tomcatStartedOccurencesIn(output)).isEqualTo(2));
} }
private int tomcatStartedOccurencesIn(CharSequence output) { private int tomcatStartedOccurencesIn(CharSequence output) {

View File

@ -85,10 +85,10 @@ class EndpointIdTests {
} }
@Test @Test
void ofWhenContainsDeprecatedCharsLogsWarning(CapturedOutput capturedOutput) { void ofWhenContainsDeprecatedCharsLogsWarning(CapturedOutput output) {
EndpointId.resetLoggedWarnings(); EndpointId.resetLoggedWarnings();
EndpointId.of("foo-bar"); EndpointId.of("foo-bar");
assertThat(capturedOutput.toString()) assertThat(output)
.contains("Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format"); .contains("Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format");
} }

View File

@ -55,30 +55,30 @@ public class FreeMarkerAutoConfigurationTests {
} }
@Test @Test
void nonExistentTemplateLocation(CapturedOutput capturedOutput) { void nonExistentTemplateLocation(CapturedOutput output) {
this.contextRunner this.contextRunner
.withPropertyValues("spring.freemarker.templateLoaderPath:" .withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/also-does-not-exist") + "classpath:/does-not-exist/,classpath:/also-does-not-exist")
.run((context) -> assertThat(capturedOutput).contains("Cannot find template location")); .run((context) -> assertThat(output).contains("Cannot find template location"));
} }
@Test @Test
void emptyTemplateLocation(CapturedOutput capturedOutput) { void emptyTemplateLocation(CapturedOutput output) {
File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory"); File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory");
emptyDirectory.mkdirs(); emptyDirectory.mkdirs();
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.freemarker.templateLoaderPath:" + "classpath:/empty-templates/empty-directory/") "spring.freemarker.templateLoaderPath:" + "classpath:/empty-templates/empty-directory/")
.run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); .run((context) -> assertThat(output).doesNotContain("Cannot find template location"));
} }
@Test @Test
void nonExistentLocationAndEmptyLocation(CapturedOutput capturedOutput) { void nonExistentLocationAndEmptyLocation(CapturedOutput output) {
new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs();
this.contextRunner this.contextRunner
.withPropertyValues("spring.freemarker.templateLoaderPath:" .withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/") + "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/")
.run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); .run((context) -> assertThat(output).doesNotContain("Cannot find template location"));
} }
public static class DataModel { public static class DataModel {

View File

@ -125,12 +125,12 @@ class H2ConsoleAutoConfigurationTests {
@Test @Test
@ExtendWith(OutputCaptureExtension.class) @ExtendWith(OutputCaptureExtension.class)
void dataSourceUrlIsLoggedWhenAvailable(CapturedOutput capturedOutput) throws BeansException, SQLException { void dataSourceUrlIsLoggedWhenAvailable(CapturedOutput output) throws BeansException, SQLException {
this.context.register(DataSourceAutoConfiguration.class, H2ConsoleAutoConfiguration.class); this.context.register(DataSourceAutoConfiguration.class, H2ConsoleAutoConfiguration.class);
TestPropertyValues.of("spring.h2.console.enabled:true").applyTo(this.context); TestPropertyValues.of("spring.h2.console.enabled:true").applyTo(this.context);
this.context.refresh(); this.context.refresh();
try (Connection connection = this.context.getBean(DataSource.class).getConnection()) { try (Connection connection = this.context.getBean(DataSource.class).getConnection()) {
assertThat(capturedOutput).contains("Database available at '" + connection.getMetaData().getURL() + "'"); assertThat(output).contains("Database available at '" + connection.getMetaData().getURL() + "'");
} }
} }

View File

@ -59,47 +59,47 @@ class ConditionEvaluationReportLoggingListenerTests {
private ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener(); private ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener();
@Test @Test
void logsDebugOnContextRefresh(CapturedOutput capturedOutput) { void logsDebugOnContextRefresh(CapturedOutput output) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context); this.initializer.initialize(context);
context.register(Config.class); context.register(Config.class);
context.refresh(); context.refresh();
withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context))); withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context)));
assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT"); assertThat(output).contains("CONDITIONS EVALUATION REPORT");
} }
@Test @Test
void logsDebugOnError(CapturedOutput capturedOutput) { void logsDebugOnError(CapturedOutput output) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context); this.initializer.initialize(context);
context.register(ErrorConfig.class); context.register(ErrorConfig.class);
assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh)
.satisfies((ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent( .satisfies((ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent(
new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex))));
assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT"); assertThat(output).contains("CONDITIONS EVALUATION REPORT");
} }
@Test @Test
void logsInfoOnErrorIfDebugDisabled(CapturedOutput capturedOutput) { void logsInfoOnErrorIfDebugDisabled(CapturedOutput output) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context); this.initializer.initialize(context);
context.register(ErrorConfig.class); context.register(ErrorConfig.class);
assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh).satisfies((ex) -> this.initializer assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh).satisfies((ex) -> this.initializer
.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex))); .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)));
assertThat(capturedOutput) assertThat(output)
.contains("Error starting" + " ApplicationContext. To display the conditions report re-run" .contains("Error starting" + " ApplicationContext. To display the conditions report re-run"
+ " your application with 'debug' enabled."); + " your application with 'debug' enabled.");
} }
@Test @Test
void logsOutput(CapturedOutput capturedOutput) { void logsOutput(CapturedOutput output) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context); this.initializer.initialize(context);
context.register(Config.class); context.register(Config.class);
ConditionEvaluationReport.get(context.getBeanFactory()).recordExclusions(Arrays.asList("com.foo.Bar")); ConditionEvaluationReport.get(context.getBeanFactory()).recordExclusions(Arrays.asList("com.foo.Bar"));
context.refresh(); context.refresh();
withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context))); withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context)));
assertThat(capturedOutput).contains("not a servlet web application (OnWebApplicationCondition)"); assertThat(output).contains("not a servlet web application (OnWebApplicationCondition)");
} }
@Test @Test
@ -122,7 +122,7 @@ class ConditionEvaluationReportLoggingListenerTests {
} }
@Test @Test
void listenerWithInfoLevelShouldLogAtInfo(CapturedOutput capturedOutput) { void listenerWithInfoLevelShouldLogAtInfo(CapturedOutput output) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener( ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener(
LogLevel.INFO); LogLevel.INFO);
@ -130,7 +130,7 @@ class ConditionEvaluationReportLoggingListenerTests {
context.register(Config.class); context.register(Config.class);
context.refresh(); context.refresh();
initializer.onApplicationEvent(new ContextRefreshedEvent(context)); initializer.onApplicationEvent(new ContextRefreshedEvent(context));
assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT"); assertThat(output).contains("CONDITIONS EVALUATION REPORT");
} }
@Test @Test
@ -141,10 +141,10 @@ class ConditionEvaluationReportLoggingListenerTests {
} }
@Test @Test
void noErrorIfNotInitialized(CapturedOutput capturedOutput) { void noErrorIfNotInitialized(CapturedOutput output) {
this.initializer.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], null, this.initializer.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], null,
new RuntimeException("Planned"))); new RuntimeException("Planned")));
assertThat(capturedOutput).contains("Unable to provide the conditions report"); assertThat(output).contains("Unable to provide the conditions report");
} }
private void withDebugLogging(Runnable runnable) { private void withDebugLogging(Runnable runnable) {

View File

@ -154,7 +154,7 @@ class QuartzAutoConfigurationTests {
} }
@Test @Test
void withConfiguredJobAndTrigger(CapturedOutput capturedOutput) { void withConfiguredJobAndTrigger(CapturedOutput output) {
this.contextRunner.withUserConfiguration(QuartzFullConfiguration.class) this.contextRunner.withUserConfiguration(QuartzFullConfiguration.class)
.withPropertyValues("test-name=withConfiguredJobAndTrigger").run((context) -> { .withPropertyValues("test-name=withConfiguredJobAndTrigger").run((context) -> {
assertThat(context).hasSingleBean(Scheduler.class); assertThat(context).hasSingleBean(Scheduler.class);
@ -162,7 +162,7 @@ class QuartzAutoConfigurationTests {
assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))).isNotNull(); assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))).isNotNull();
assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))).isNotNull(); assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))).isNotNull();
Thread.sleep(1000L); Thread.sleep(1000L);
assertThat(capturedOutput).contains("withConfiguredJobAndTrigger").contains("jobDataValue"); assertThat(output).contains("withConfiguredJobAndTrigger").contains("jobDataValue");
}); });
} }

View File

@ -55,17 +55,15 @@ import org.springframework.web.bind.annotation.RestController;
class SecurityFilterAutoConfigurationEarlyInitializationTests { class SecurityFilterAutoConfigurationEarlyInitializationTests {
@Test @Test
void testSecurityFilterDoesNotCauseEarlyInitialization(CapturedOutput capturedOutput) { void testSecurityFilterDoesNotCauseEarlyInitialization(CapturedOutput output) {
try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext()) { try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext()) {
TestPropertyValues.of("server.port:0").applyTo(context); TestPropertyValues.of("server.port:0").applyTo(context);
context.register(Config.class); context.register(Config.class);
context.refresh(); context.refresh();
int port = context.getWebServer().getPort(); int port = context.getWebServer().getPort();
String password = capturedOutput.toString().split("Using generated security password: ")[1].split("\n")[0] String password = output.toString().split("Using generated security password: ")[1].split("\n")[0].trim();
.trim();
new TestRestTemplate("user", password).getForEntity("http://localhost:" + port, Object.class); new TestRestTemplate("user", password).getForEntity("http://localhost:" + port, Object.class);
// If early initialization occurred a ConverterNotFoundException is thrown // If early initialization occurred a ConverterNotFoundException is thrown
} }
} }

View File

@ -60,40 +60,40 @@ class UserDetailsServiceAutoConfigurationTests {
.withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class));
@Test @Test
void testDefaultUsernamePassword(CapturedOutput capturedOutput) { void testDefaultUsernamePassword(CapturedOutput output) {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
UserDetailsService manager = context.getBean(UserDetailsService.class); UserDetailsService manager = context.getBean(UserDetailsService.class);
assertThat(capturedOutput.toString()).contains("Using generated security password:"); assertThat(output).contains("Using generated security password:");
assertThat(manager.loadUserByUsername("user")).isNotNull(); assertThat(manager.loadUserByUsername("user")).isNotNull();
}); });
} }
@Test @Test
void defaultUserNotCreatedIfAuthenticationManagerBeanPresent(CapturedOutput capturedOutput) { void defaultUserNotCreatedIfAuthenticationManagerBeanPresent(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestAuthenticationManagerConfiguration.class).run((context) -> { this.contextRunner.withUserConfiguration(TestAuthenticationManagerConfiguration.class).run((context) -> {
AuthenticationManager manager = context.getBean(AuthenticationManager.class); AuthenticationManager manager = context.getBean(AuthenticationManager.class);
assertThat(manager) assertThat(manager)
.isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager); .isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager);
assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); assertThat(output).doesNotContain("Using generated security password: ");
TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar");
assertThat(manager.authenticate(token)).isNotNull(); assertThat(manager.authenticate(token)).isNotNull();
}); });
} }
@Test @Test
void defaultUserNotCreatedIfUserDetailsServiceBeanPresent(CapturedOutput capturedOutput) { void defaultUserNotCreatedIfUserDetailsServiceBeanPresent(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestUserDetailsServiceConfiguration.class).run((context) -> { this.contextRunner.withUserConfiguration(TestUserDetailsServiceConfiguration.class).run((context) -> {
UserDetailsService userDetailsService = context.getBean(UserDetailsService.class); UserDetailsService userDetailsService = context.getBean(UserDetailsService.class);
assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); assertThat(output).doesNotContain("Using generated security password: ");
assertThat(userDetailsService.loadUserByUsername("foo")).isNotNull(); assertThat(userDetailsService.loadUserByUsername("foo")).isNotNull();
}); });
} }
@Test @Test
void defaultUserNotCreatedIfAuthenticationProviderBeanPresent(CapturedOutput capturedOutput) { void defaultUserNotCreatedIfAuthenticationProviderBeanPresent(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestAuthenticationProviderConfiguration.class).run((context) -> { this.contextRunner.withUserConfiguration(TestAuthenticationProviderConfiguration.class).run((context) -> {
AuthenticationProvider provider = context.getBean(AuthenticationProvider.class); AuthenticationProvider provider = context.getBean(AuthenticationProvider.class);
assertThat(capturedOutput.toString()).doesNotContain("Using generated security password: "); assertThat(output).doesNotContain("Using generated security password: ");
TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar");
assertThat(provider.authenticate(token)).isNotNull(); assertThat(provider.authenticate(token)).isNotNull();
}); });
@ -131,10 +131,9 @@ class UserDetailsServiceAutoConfigurationTests {
} }
@Test @Test
void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed(CapturedOutput capturedOutput) { void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed(CapturedOutput output) {
this.contextRunner.withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class) this.contextRunner.withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class)
.run(((context) -> assertThat(capturedOutput.toString()) .run(((context) -> assertThat(output).doesNotContain("Using generated security password: ")));
.doesNotContain("Using generated security password: ")));
} }
private void testPasswordEncoding(Class<?> configClass, String providedPassword, String expectedPassword) { private void testPasswordEncoding(Class<?> configClass, String providedPassword, String expectedPassword) {

View File

@ -98,13 +98,13 @@ class TaskExecutionAutoConfigurationTests {
} }
@Test @Test
void taskExecutorAutoConfigured(CapturedOutput capturedOutput) { void taskExecutorAutoConfigured(CapturedOutput output) {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
assertThat(capturedOutput).doesNotContain("Initializing ExecutorService"); assertThat(output).doesNotContain("Initializing ExecutorService");
assertThat(context).hasSingleBean(Executor.class); assertThat(context).hasSingleBean(Executor.class);
assertThat(context).hasBean("applicationTaskExecutor"); assertThat(context).hasBean("applicationTaskExecutor");
assertThat(context).getBean("applicationTaskExecutor").isInstanceOf(ThreadPoolTaskExecutor.class); assertThat(context).getBean("applicationTaskExecutor").isInstanceOf(ThreadPoolTaskExecutor.class);
assertThat(capturedOutput).contains("Initializing ExecutorService"); assertThat(output).contains("Initializing ExecutorService");
}); });
} }

View File

@ -159,16 +159,16 @@ class ThymeleafReactiveAutoConfigurationTests {
} }
@Test @Test
void templateLocationDoesNotExist(CapturedOutput capturedOutput) { void templateLocationDoesNotExist(CapturedOutput output) {
this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/")
.run((context) -> assertThat(capturedOutput).contains("Cannot find template location")); .run((context) -> assertThat(output).contains("Cannot find template location"));
} }
@Test @Test
void templateLocationEmpty(CapturedOutput capturedOutput) { void templateLocationEmpty(CapturedOutput output) {
new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs();
this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/")
.run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); .run((context) -> assertThat(output).doesNotContain("Cannot find template location"));
} }
@Test @Test

View File

@ -165,16 +165,16 @@ class ThymeleafServletAutoConfigurationTests {
} }
@Test @Test
void templateLocationDoesNotExist(CapturedOutput capturedOutput) { void templateLocationDoesNotExist(CapturedOutput output) {
this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/")
.run((context) -> assertThat(capturedOutput).contains("Cannot find template location")); .run((context) -> assertThat(output).contains("Cannot find template location"));
} }
@Test @Test
void templateLocationEmpty(CapturedOutput capturedOutput) { void templateLocationEmpty(CapturedOutput output) {
new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs();
this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/")
.run((context) -> assertThat(capturedOutput).doesNotContain("Cannot find template location")); .run((context) -> assertThat(output).doesNotContain("Cannot find template location"));
} }
@Test @Test

View File

@ -72,7 +72,7 @@ class DefaultErrorWebExceptionHandlerIntegrationTests {
.withUserConfiguration(Application.class); .withUserConfiguration(Application.class);
@Test @Test
void jsonError(CapturedOutput capturedOutput) { void jsonError(CapturedOutput output) {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
WebTestClient client = getWebClient(context); WebTestClient client = getWebClient(context);
client.get().uri("/").exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() client.get().uri("/").exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
@ -80,7 +80,7 @@ class DefaultErrorWebExceptionHandlerIntegrationTests {
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("path").isEqualTo(("/")) .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("path").isEqualTo(("/"))
.jsonPath("message").isEqualTo("Expected!").jsonPath("exception").doesNotExist().jsonPath("trace") .jsonPath("message").isEqualTo("Expected!").jsonPath("exception").doesNotExist().jsonPath("trace")
.doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); .doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId());
assertThat(capturedOutput).contains("500 Server Error for HTTP GET \"/\"") assertThat(output).contains("500 Server Error for HTTP GET \"/\"")
.contains("java.lang.IllegalStateException: Expected!"); .contains("java.lang.IllegalStateException: Expected!");
}); });
} }

View File

@ -63,7 +63,7 @@ class ErrorMvcAutoConfigurationTests {
} }
@Test @Test
void renderWhenAlreadyCommittedLogsMessage(CapturedOutput capturedOutput) { void renderWhenAlreadyCommittedLogsMessage(CapturedOutput output) {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
View errorView = context.getBean("error", View.class); View errorView = context.getBean("error", View.class);
ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class); ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class);
@ -71,7 +71,7 @@ class ErrorMvcAutoConfigurationTests {
true); true);
errorView.render(errorAttributes.getErrorAttributes(webRequest, true), webRequest.getRequest(), errorView.render(errorAttributes.getErrorAttributes(webRequest, true), webRequest.getRequest(),
webRequest.getResponse()); webRequest.getResponse());
assertThat(capturedOutput).contains("Cannot render error page for request [/path] " assertThat(output).contains("Cannot render error page for request [/path] "
+ "and exception [Exception message] as the response has " + "and exception [Exception message] as the response has "
+ "already been committed. As a result, the response may " + "have the wrong status code."); + "already been committed. As a result, the response may " + "have the wrong status code.");
}); });

View File

@ -36,8 +36,8 @@ class ClassLoaderIntegrationTests {
@RegisterExtension @RegisterExtension
CliTester cli; CliTester cli;
ClassLoaderIntegrationTests(CapturedOutput capturedOutput) { ClassLoaderIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/", capturedOutput); this.cli = new CliTester("src/test/resources/", output);
} }
@Test @Test

View File

@ -63,7 +63,7 @@ public class CliTester implements BeforeEachCallback, AfterEachCallback {
private final BuildOutput buildOutput = new BuildOutput(getClass()); private final BuildOutput buildOutput = new BuildOutput(getClass());
private final CapturedOutput capturedOutput; private final CapturedOutput output;
private String previousOutput = ""; private String previousOutput = "";
@ -75,7 +75,7 @@ public class CliTester implements BeforeEachCallback, AfterEachCallback {
private File serverPortFile; private File serverPortFile;
public CliTester(String prefix, CapturedOutput capturedOutput) { public CliTester(String prefix, CapturedOutput output) {
this.prefix = prefix; this.prefix = prefix;
try { try {
this.temp = Files.createTempDirectory("cli-tester").toFile(); this.temp = Files.createTempDirectory("cli-tester").toFile();
@ -83,7 +83,7 @@ public class CliTester implements BeforeEachCallback, AfterEachCallback {
catch (IOException ex) { catch (IOException ex) {
throw new IllegalStateException("Failed to create temp directory"); throw new IllegalStateException("Failed to create temp directory");
} }
this.capturedOutput = capturedOutput; this.output = output;
} }
public void setTimeout(long timeout) { public void setTimeout(long timeout) {
@ -182,7 +182,7 @@ public class CliTester implements BeforeEachCallback, AfterEachCallback {
} }
private String getOutput() { private String getOutput() {
String output = this.capturedOutput.toString().substring(this.previousOutput.length()); String output = this.output.toString().substring(this.previousOutput.length());
this.previousOutput = output; this.previousOutput = output;
return output; return output;
} }

View File

@ -36,8 +36,8 @@ class DirectorySourcesIntegrationTests {
@RegisterExtension @RegisterExtension
CliTester cli; CliTester cli;
DirectorySourcesIntegrationTests(CapturedOutput capturedOutput) { DirectorySourcesIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/dir-sample/", capturedOutput); this.cli = new CliTester("src/test/resources/dir-sample/", output);
} }
@Test @Test

View File

@ -44,8 +44,8 @@ class GrabCommandIntegrationTests {
@RegisterExtension @RegisterExtension
CliTester cli; CliTester cli;
GrabCommandIntegrationTests(CapturedOutput capturedOutput) { GrabCommandIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/grab-samples/", capturedOutput); this.cli = new CliTester("src/test/resources/grab-samples/", output);
} }
@BeforeEach @BeforeEach

View File

@ -41,8 +41,8 @@ class ReproIntegrationTests {
@RegisterExtension @RegisterExtension
CliTester cli; CliTester cli;
ReproIntegrationTests(CapturedOutput capturedOutput) { ReproIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/repro-samples/", capturedOutput); this.cli = new CliTester("src/test/resources/repro-samples/", output);
} }
@Test @Test

View File

@ -41,8 +41,8 @@ class RunCommandIntegrationTests {
@RegisterExtension @RegisterExtension
CliTester cli; CliTester cli;
RunCommandIntegrationTests(CapturedOutput capturedOutput) { RunCommandIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/it/resources/run-command/", capturedOutput); this.cli = new CliTester("src/it/resources/run-command/", output);
} }
private Properties systemProperties = new Properties(); private Properties systemProperties = new Properties();

View File

@ -43,8 +43,8 @@ class SampleIntegrationTests {
@RegisterExtension @RegisterExtension
CliTester cli; CliTester cli;
SampleIntegrationTests(CapturedOutput capturedOutput) { SampleIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("samples/", capturedOutput); this.cli = new CliTester("samples/", output);
} }
@Test @Test

View File

@ -78,21 +78,21 @@ class RemoteClientConfigurationTests {
} }
@Test @Test
void warnIfRestartDisabled(CapturedOutput capturedOutput) { void warnIfRestartDisabled(CapturedOutput output) {
configure("spring.devtools.remote.restart.enabled:false"); configure("spring.devtools.remote.restart.enabled:false");
assertThat(capturedOutput).contains("Remote restart is disabled"); assertThat(output).contains("Remote restart is disabled");
} }
@Test @Test
void warnIfNotHttps(CapturedOutput capturedOutput) { void warnIfNotHttps(CapturedOutput output) {
configure("http://localhost", true); configure("http://localhost", true);
assertThat(capturedOutput).contains("is insecure"); assertThat(output).contains("is insecure");
} }
@Test @Test
void doesntWarnIfUsingHttps(CapturedOutput capturedOutput) { void doesntWarnIfUsingHttps(CapturedOutput output) {
configure("https://localhost", true); configure("https://localhost", true);
assertThat(capturedOutput).doesNotContain("is insecure"); assertThat(output).doesNotContain("is insecure");
} }
@Test @Test

View File

@ -80,11 +80,11 @@ class RestartApplicationListenerTests {
} }
@Test @Test
void disableWithSystemProperty(CapturedOutput capturedOutput) { void disableWithSystemProperty(CapturedOutput output) {
System.setProperty(ENABLED_PROPERTY, "false"); System.setProperty(ENABLED_PROPERTY, "false");
testInitialize(false); testInitialize(false);
assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("enabled", false); assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("enabled", false);
assertThat(capturedOutput).contains("Restart disabled due to System property"); assertThat(output).contains("Restart disabled due to System property");
} }
private void testInitialize(boolean failed) { private void testInitialize(boolean failed) {

View File

@ -76,14 +76,13 @@ class RestarterTests {
} }
@Test @Test
void testRestart(CapturedOutput capturedOutput) throws Exception { void testRestart(CapturedOutput output) throws Exception {
Restarter.clearInstance(); Restarter.clearInstance();
Thread thread = new Thread(SampleApplication::main); Thread thread = new Thread(SampleApplication::main);
thread.start(); thread.start();
Thread.sleep(2600); Thread.sleep(2600);
String output = capturedOutput.toString(); assertThat(StringUtils.countOccurrencesOf(output.toString(), "Tick 0")).isGreaterThan(1);
assertThat(StringUtils.countOccurrencesOf(output, "Tick 0")).isGreaterThan(1); assertThat(StringUtils.countOccurrencesOf(output.toString(), "Tick 1")).isGreaterThan(1);
assertThat(StringUtils.countOccurrencesOf(output, "Tick 1")).isGreaterThan(1);
assertThat(CloseCountingApplicationListener.closed).isGreaterThan(0); assertThat(CloseCountingApplicationListener.closed).isGreaterThan(0);
} }

View File

@ -139,11 +139,11 @@ class HttpTunnelConnectionTests {
} }
@Test @Test
void connectFailureLogsWarning(CapturedOutput capturedOutput) throws Exception { void connectFailureLogsWarning(CapturedOutput output) throws Exception {
this.requestFactory.willRespond(new ConnectException()); this.requestFactory.willRespond(new ConnectException());
TunnelChannel tunnel = openTunnel(true); TunnelChannel tunnel = openTunnel(true);
assertThat(tunnel.isOpen()).isFalse(); assertThat(tunnel.isOpen()).isFalse();
assertThat(capturedOutput).contains("Failed to connect to remote application at http://localhost:12345"); assertThat(output).contains("Failed to connect to remote application at http://localhost:12345");
} }
private void write(TunnelChannel channel, String string) throws IOException { private void write(TunnelChannel channel, String string) throws IOException {

View File

@ -33,11 +33,11 @@ import static org.assertj.core.api.Assertions.assertThat;
class SpringApplicationBuilderExampleTests { class SpringApplicationBuilderExampleTests {
@Test @Test
void contextHierarchyWithDisabledBanner(CapturedOutput capturedOutput) { void contextHierarchyWithDisabledBanner(CapturedOutput output) {
System.setProperty("spring.main.web-application-type", "none"); System.setProperty("spring.main.web-application-type", "none");
try { try {
new SpringApplicationBuilderExample().hierarchyWithDisabledBanner(new String[0]); new SpringApplicationBuilderExample().hierarchyWithDisabledBanner(new String[0]);
assertThat(capturedOutput).doesNotContain(":: Spring Boot ::"); assertThat(output).doesNotContain(":: Spring Boot ::");
} }
finally { finally {
System.clearProperty("spring.main.web-application-type"); System.clearProperty("spring.main.web-application-type");

View File

@ -46,9 +46,9 @@ class PropertiesMigrationListenerTests {
} }
@Test @Test
void sampleReport(CapturedOutput capturedOutput) { void sampleReport(CapturedOutput output) {
this.context = createSampleApplication().run("--banner.charset=UTF8"); this.context = createSampleApplication().run("--banner.charset=UTF8");
assertThat(capturedOutput).contains("commandLineArgs").contains("spring.banner.charset") assertThat(output).contains("commandLineArgs").contains("spring.banner.charset")
.contains("Each configuration key has been temporarily mapped") .contains("Each configuration key has been temporarily mapped")
.doesNotContain("Please refer to the migration guide"); .doesNotContain("Please refer to the migration guide");
} }

View File

@ -53,7 +53,7 @@ class SpringBootDependencyInjectionTestExecutionListenerTests {
} }
@Test @Test
void prepareFailingTestInstanceShouldPrintReport(CapturedOutput capturedOutput) throws Exception { void prepareFailingTestInstanceShouldPrintReport(CapturedOutput output) throws Exception {
TestContext testContext = mock(TestContext.class); TestContext testContext = mock(TestContext.class);
given(testContext.getTestInstance()).willThrow(new IllegalStateException()); given(testContext.getTestInstance()).willThrow(new IllegalStateException());
SpringApplication application = new SpringApplication(Config.class); SpringApplication application = new SpringApplication(Config.class);
@ -66,7 +66,7 @@ class SpringBootDependencyInjectionTestExecutionListenerTests {
catch (IllegalStateException ex) { catch (IllegalStateException ex) {
// Expected // Expected
} }
assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT").contains("Positive matches") assertThat(output).contains("CONDITIONS EVALUATION REPORT").contains("Positive matches")
.contains("Negative matches"); .contains("Negative matches");
} }

View File

@ -57,9 +57,9 @@ class MockMvcSpringBootTestIntegrationTests {
private MockMvc mvc; private MockMvc mvc;
@Test @Test
void shouldFindController1(CapturedOutput capturedOutput) throws Exception { void shouldFindController1(CapturedOutput output) throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(capturedOutput).contains("Request URI = /one"); assertThat(output).contains("Request URI = /one");
} }
@Test @Test

View File

@ -47,9 +47,9 @@ class WebMvcTestPrintAlwaysIntegrationTests {
private MockMvc mvc; private MockMvc mvc;
@Test @Test
void shouldPrint(CapturedOutput capturedOutput) throws Exception { void shouldPrint(CapturedOutput output) throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(capturedOutput).contains("Request URI = /one"); assertThat(output).contains("Request URI = /one");
} }
} }

View File

@ -47,15 +47,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
class WebMvcTestPrintDefaultIntegrationTests { class WebMvcTestPrintDefaultIntegrationTests {
@Test @Test
void shouldNotPrint(CapturedOutput capturedOutput) { void shouldNotPrint(CapturedOutput output) {
executeTests(ShouldNotPrint.class); executeTests(ShouldNotPrint.class);
assertThat(capturedOutput).doesNotContain("HTTP Method"); assertThat(output).doesNotContain("HTTP Method");
} }
@Test @Test
void shouldPrint(CapturedOutput capturedOutput) { void shouldPrint(CapturedOutput output) {
executeTests(ShouldPrint.class); executeTests(ShouldPrint.class);
assertThat(capturedOutput).contains("HTTP Method"); assertThat(output).contains("HTTP Method");
} }
private void executeTests(Class<?> testClass) { private void executeTests(Class<?> testClass) {

View File

@ -47,9 +47,9 @@ class WebMvcTestPrintDefaultOverrideIntegrationTests {
private MockMvc mvc; private MockMvc mvc;
@Test @Test
void shouldFindController1(CapturedOutput capturedOutput) throws Exception { void shouldFindController1(CapturedOutput output) throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(capturedOutput).doesNotContain("Request URI = /one"); assertThat(output).doesNotContain("Request URI = /one");
} }
} }

View File

@ -48,9 +48,9 @@ class WebMvcTestPrintOverrideIntegrationTests {
private MockMvc mvc; private MockMvc mvc;
@Test @Test
void shouldNotPrint(CapturedOutput capturedOutput) throws Exception { void shouldNotPrint(CapturedOutput output) throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk()); this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(capturedOutput).doesNotContain("Request URI = /one"); assertThat(output).doesNotContain("Request URI = /one");
} }
} }

View File

@ -59,13 +59,13 @@ class PropertiesLauncherTests {
private ClassLoader contextClassLoader; private ClassLoader contextClassLoader;
private CapturedOutput capturedOutput; private CapturedOutput output;
@BeforeEach @BeforeEach
void setup(CapturedOutput capturedOutput) { void setup(CapturedOutput capturedOutput) {
this.contextClassLoader = Thread.currentThread().getContextClassLoader(); this.contextClassLoader = Thread.currentThread().getContextClassLoader();
System.setProperty("loader.home", new File("src/test/resources").getAbsolutePath()); System.setProperty("loader.home", new File("src/test/resources").getAbsolutePath());
this.capturedOutput = capturedOutput; this.output = capturedOutput;
} }
@AfterEach @AfterEach
@ -312,8 +312,8 @@ class PropertiesLauncherTests {
manifest.getMainAttributes().putValue("Loader-Path", "/foo.jar, /bar"); manifest.getMainAttributes().putValue("Loader-Path", "/foo.jar, /bar");
File manifestFile = new File(this.tempDir, "META-INF/MANIFEST.MF"); File manifestFile = new File(this.tempDir, "META-INF/MANIFEST.MF");
manifestFile.getParentFile().mkdirs(); manifestFile.getParentFile().mkdirs();
try (FileOutputStream output = new FileOutputStream(manifestFile)) { try (FileOutputStream manifestStream = new FileOutputStream(manifestFile)) {
manifest.write(output); manifest.write(manifestStream);
} }
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertThat((List<String>) ReflectionTestUtils.getField(launcher, "paths")).containsExactly("/foo.jar", "/bar/"); assertThat((List<String>) ReflectionTestUtils.getField(launcher, "paths")).containsExactly("/foo.jar", "/bar/");
@ -344,7 +344,7 @@ class PropertiesLauncherTests {
while (!timeout && count < 100) { while (!timeout && count < 100) {
count++; count++;
Thread.sleep(50L); Thread.sleep(50L);
timeout = this.capturedOutput.toString().contains(value); timeout = this.output.toString().contains(value);
} }
assertThat(timeout).as("Timed out waiting for (" + value + ")").isTrue(); assertThat(timeout).as("Timed out waiting for (" + value + ")").isTrue();
} }

View File

@ -68,25 +68,25 @@ class BannerTests {
} }
@Test @Test
void testDefaultBanner(CapturedOutput capturedOutput) { void testDefaultBanner(CapturedOutput output) {
SpringApplication application = createSpringApplication(); SpringApplication application = createSpringApplication();
this.context = application.run(); this.context = application.run();
assertThat(capturedOutput).contains(":: Spring Boot ::"); assertThat(output).contains(":: Spring Boot ::");
} }
@Test @Test
void testDefaultBannerInLog(CapturedOutput capturedOutput) { void testDefaultBannerInLog(CapturedOutput output) {
SpringApplication application = createSpringApplication(); SpringApplication application = createSpringApplication();
this.context = application.run(); this.context = application.run();
assertThat(capturedOutput).contains(":: Spring Boot ::"); assertThat(output).contains(":: Spring Boot ::");
} }
@Test @Test
void testCustomBanner(CapturedOutput capturedOutput) { void testCustomBanner(CapturedOutput output) {
SpringApplication application = createSpringApplication(); SpringApplication application = createSpringApplication();
application.setBanner(new DummyBanner()); application.setBanner(new DummyBanner());
this.context = application.run(); this.context = application.run();
assertThat(capturedOutput).contains("My Banner"); assertThat(output).contains("My Banner");
} }
@Test @Test

View File

@ -49,27 +49,27 @@ class SimpleMainTests {
} }
@Test @Test
void basePackageScan(CapturedOutput capturedOutput) throws Exception { void basePackageScan(CapturedOutput output) throws Exception {
SpringApplication.main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig")); SpringApplication.main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig"));
assertThat(capturedOutput).contains(SPRING_STARTUP); assertThat(output).contains(SPRING_STARTUP);
} }
@Test @Test
void configClassContext(CapturedOutput capturedOutput) throws Exception { void configClassContext(CapturedOutput output) throws Exception {
SpringApplication.main(getArgs(getClass().getName())); SpringApplication.main(getArgs(getClass().getName()));
assertThat(capturedOutput).contains(SPRING_STARTUP); assertThat(output).contains(SPRING_STARTUP);
} }
@Test @Test
void xmlContext(CapturedOutput capturedOutput) throws Exception { void xmlContext(CapturedOutput output) throws Exception {
SpringApplication.main(getArgs("org/springframework/boot/sample-beans.xml")); SpringApplication.main(getArgs("org/springframework/boot/sample-beans.xml"));
assertThat(capturedOutput).contains(SPRING_STARTUP); assertThat(output).contains(SPRING_STARTUP);
} }
@Test @Test
void mixedContext(CapturedOutput capturedOutput) throws Exception { void mixedContext(CapturedOutput output) throws Exception {
SpringApplication.main(getArgs(getClass().getName(), "org/springframework/boot/sample-beans.xml")); SpringApplication.main(getArgs(getClass().getName(), "org/springframework/boot/sample-beans.xml"));
assertThat(capturedOutput).contains(SPRING_STARTUP); assertThat(output).contains(SPRING_STARTUP);
} }
private String[] getArgs(String... args) { private String[] getArgs(String... args) {

View File

@ -188,24 +188,24 @@ class SpringApplicationTests {
} }
@Test @Test
void customBanner(CapturedOutput capturedOutput) { void customBanner(CapturedOutput output) {
SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); SpringApplication application = spy(new SpringApplication(ExampleConfig.class));
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run("--spring.banner.location=classpath:test-banner.txt"); this.context = application.run("--spring.banner.location=classpath:test-banner.txt");
assertThat(capturedOutput).startsWith("Running a Test!"); assertThat(output).startsWith("Running a Test!");
} }
@Test @Test
void customBannerWithProperties(CapturedOutput capturedOutput) { void customBannerWithProperties(CapturedOutput output) {
SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); SpringApplication application = spy(new SpringApplication(ExampleConfig.class));
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run("--spring.banner.location=classpath:test-banner-with-placeholder.txt", this.context = application.run("--spring.banner.location=classpath:test-banner-with-placeholder.txt",
"--test.property=123456"); "--test.property=123456");
assertThat(capturedOutput).containsPattern("Running a Test!\\s+123456"); assertThat(output).containsPattern("Running a Test!\\s+123456");
} }
@Test @Test
void imageBannerAndTextBanner(CapturedOutput capturedOutput) { void imageBannerAndTextBanner(CapturedOutput output) {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
MockResourceLoader resourceLoader = new MockResourceLoader(); MockResourceLoader resourceLoader = new MockResourceLoader();
resourceLoader.addResource("banner.gif", "black-and-white.gif"); resourceLoader.addResource("banner.gif", "black-and-white.gif");
@ -213,47 +213,47 @@ class SpringApplicationTests {
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
application.setResourceLoader(resourceLoader); application.setResourceLoader(resourceLoader);
application.run(); application.run();
assertThat(capturedOutput).contains("@@@@").contains("Foo Bar"); assertThat(output).contains("@@@@").contains("Foo Bar");
} }
@Test @Test
void imageBannerLoads(CapturedOutput capturedOutput) { void imageBannerLoads(CapturedOutput output) {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
MockResourceLoader resourceLoader = new MockResourceLoader(); MockResourceLoader resourceLoader = new MockResourceLoader();
resourceLoader.addResource("banner.gif", "black-and-white.gif"); resourceLoader.addResource("banner.gif", "black-and-white.gif");
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
application.setResourceLoader(resourceLoader); application.setResourceLoader(resourceLoader);
application.run(); application.run();
assertThat(capturedOutput).contains("@@@@@@"); assertThat(output).contains("@@@@@@");
} }
@Test @Test
void logsNoActiveProfiles(CapturedOutput capturedOutput) { void logsNoActiveProfiles(CapturedOutput output) {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run(); this.context = application.run();
assertThat(capturedOutput).contains("No active profile set, falling back to default profiles: default"); assertThat(output).contains("No active profile set, falling back to default profiles: default");
} }
@Test @Test
void logsActiveProfiles(CapturedOutput capturedOutput) { void logsActiveProfiles(CapturedOutput output) {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run("--spring.profiles.active=myprofiles"); this.context = application.run("--spring.profiles.active=myprofiles");
assertThat(capturedOutput).contains("The following profiles are active: myprofile"); assertThat(output).contains("The following profiles are active: myprofile");
} }
@Test @Test
void enableBannerInLogViaProperty(CapturedOutput capturedOutput) { void enableBannerInLogViaProperty(CapturedOutput output) {
SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); SpringApplication application = spy(new SpringApplication(ExampleConfig.class));
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run("--spring.main.banner-mode=log"); this.context = application.run("--spring.main.banner-mode=log");
verify(application, atLeastOnce()).setBannerMode(Banner.Mode.LOG); verify(application, atLeastOnce()).setBannerMode(Banner.Mode.LOG);
assertThat(capturedOutput).contains("o.s.b.SpringApplication"); assertThat(output).contains("o.s.b.SpringApplication");
} }
@Test @Test
void setIgnoreBeanInfoPropertyByDefault(CapturedOutput capturedOutput) { void setIgnoreBeanInfoPropertyByDefault(CapturedOutput output) {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run(); this.context = application.run();
@ -627,7 +627,7 @@ class SpringApplicationTests {
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
void runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished(CapturedOutput capturedOutput) void runnersAreCalledAfterStartedIsLoggedAndBeforeApplicationReadyEventIsPublished(CapturedOutput output)
throws Exception { throws Exception {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
ApplicationRunner applicationRunner = mock(ApplicationRunner.class); ApplicationRunner applicationRunner = mock(ApplicationRunner.class);
@ -635,11 +635,11 @@ class SpringApplicationTests {
application.addInitializers((context) -> { application.addInitializers((context) -> {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("commandLineRunner", (CommandLineRunner) (args) -> { beanFactory.registerSingleton("commandLineRunner", (CommandLineRunner) (args) -> {
assertThat(capturedOutput).contains("Started"); assertThat(output).contains("Started");
commandLineRunner.run(args); commandLineRunner.run(args);
}); });
beanFactory.registerSingleton("applicationRunner", (ApplicationRunner) (args) -> { beanFactory.registerSingleton("applicationRunner", (ApplicationRunner) (args) -> {
assertThat(capturedOutput).contains("Started"); assertThat(output).contains("Started");
applicationRunner.run(args); applicationRunner.run(args);
}); });
}); });
@ -706,7 +706,7 @@ class SpringApplicationTests {
} }
@Test @Test
void failureInReadyEventListenerCloseApplicationContext(CapturedOutput capturedOutput) { void failureInReadyEventListenerCloseApplicationContext(CapturedOutput output) {
SpringApplication application = new SpringApplication(ExampleConfig.class); SpringApplication application = new SpringApplication(ExampleConfig.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
ExitCodeListener exitCodeListener = new ExitCodeListener(); ExitCodeListener exitCodeListener = new ExitCodeListener();
@ -720,7 +720,7 @@ class SpringApplicationTests {
verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class));
verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class));
assertThat(exitCodeListener.getExitCode()).isEqualTo(11); assertThat(exitCodeListener.getExitCode()).isEqualTo(11);
assertThat(capturedOutput).contains("Application run failed"); assertThat(output).contains("Application run failed");
} }
@Test @Test
@ -815,7 +815,7 @@ class SpringApplicationTests {
} }
@Test @Test
void exceptionFromRefreshIsHandledGracefully(CapturedOutput capturedOutput) { void exceptionFromRefreshIsHandledGracefully(CapturedOutput output) {
final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class); final SpringBootExceptionHandler handler = mock(SpringBootExceptionHandler.class);
SpringApplication application = new SpringApplication(RefreshFailureConfig.class) { SpringApplication application = new SpringApplication(RefreshFailureConfig.class) {
@ -832,7 +832,7 @@ class SpringApplicationTests {
ArgumentCaptor<RuntimeException> exceptionCaptor = ArgumentCaptor.forClass(RuntimeException.class); ArgumentCaptor<RuntimeException> exceptionCaptor = ArgumentCaptor.forClass(RuntimeException.class);
verify(handler).registerLoggedException(exceptionCaptor.capture()); verify(handler).registerLoggedException(exceptionCaptor.capture());
assertThat(exceptionCaptor.getValue()).hasCauseInstanceOf(RefreshFailureException.class); assertThat(exceptionCaptor.getValue()).hasCauseInstanceOf(RefreshFailureException.class);
assertThat(capturedOutput).doesNotContain("NullPointerException"); assertThat(output).doesNotContain("NullPointerException");
} }
@Test @Test
@ -1046,19 +1046,21 @@ class SpringApplicationTests {
} }
@Test @Test
void failureResultsInSingleStackTrace(CapturedOutput capturedOutput) throws Exception { void failureResultsInSingleStackTrace(CapturedOutput output) throws Exception {
ThreadGroup group = new ThreadGroup("main"); ThreadGroup group = new ThreadGroup("main");
Thread thread = new Thread(group, "main") { Thread thread = new Thread(group, "main") {
@Override @Override
public void run() { public void run() {
SpringApplication application = new SpringApplication(FailingConfig.class); SpringApplication application = new SpringApplication(FailingConfig.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
application.run(); application.run();
} }
}; };
thread.start(); thread.start();
thread.join(6000); thread.join(6000);
assertThat(capturedOutput).containsOnlyOnce("Caused by: java.lang.RuntimeException: ExpectedError"); assertThat(output).containsOnlyOnce("Caused by: java.lang.RuntimeException: ExpectedError");
} }
@Test @Test

View File

@ -54,57 +54,57 @@ class ConfigurationWarningsApplicationContextInitializerTests {
+ "start due to a @ComponentScan of 'org.springframework'."; + "start due to a @ComponentScan of 'org.springframework'.";
@Test @Test
void logWarningInDefaultPackage(CapturedOutput capturedOutput) { void logWarningInDefaultPackage(CapturedOutput output) {
load(InDefaultPackageConfiguration.class); load(InDefaultPackageConfiguration.class);
assertThat(capturedOutput).contains(DEFAULT_SCAN_WARNING); assertThat(output).contains(DEFAULT_SCAN_WARNING);
} }
@Test @Test
void logWarningInDefaultPackageAndMetaAnnotation(CapturedOutput capturedOutput) { void logWarningInDefaultPackageAndMetaAnnotation(CapturedOutput output) {
load(InDefaultPackageWithMetaAnnotationConfiguration.class); load(InDefaultPackageWithMetaAnnotationConfiguration.class);
assertThat(capturedOutput).contains(DEFAULT_SCAN_WARNING); assertThat(output).contains(DEFAULT_SCAN_WARNING);
} }
@Test @Test
void noLogIfInRealPackage(CapturedOutput capturedOutput) { void noLogIfInRealPackage(CapturedOutput output) {
load(InRealPackageConfiguration.class); load(InRealPackageConfiguration.class);
assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); assertThat(output).doesNotContain(DEFAULT_SCAN_WARNING);
} }
@Test @Test
void noLogWithoutComponentScanAnnotation(CapturedOutput capturedOutput) { void noLogWithoutComponentScanAnnotation(CapturedOutput output) {
load(InDefaultPackageWithoutScanConfiguration.class); load(InDefaultPackageWithoutScanConfiguration.class);
assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); assertThat(output).doesNotContain(DEFAULT_SCAN_WARNING);
} }
@Test @Test
void noLogIfHasValue(CapturedOutput capturedOutput) { void noLogIfHasValue(CapturedOutput output) {
load(InDefaultPackageWithValueConfiguration.class); load(InDefaultPackageWithValueConfiguration.class);
assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); assertThat(output).doesNotContain(DEFAULT_SCAN_WARNING);
} }
@Test @Test
void noLogIfHasBasePackages(CapturedOutput capturedOutput) { void noLogIfHasBasePackages(CapturedOutput output) {
load(InDefaultPackageWithBasePackagesConfiguration.class); load(InDefaultPackageWithBasePackagesConfiguration.class);
assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); assertThat(output).doesNotContain(DEFAULT_SCAN_WARNING);
} }
@Test @Test
void noLogIfHasBasePackageClasses(CapturedOutput capturedOutput) { void noLogIfHasBasePackageClasses(CapturedOutput output) {
load(InDefaultPackageWithBasePackageClassesConfiguration.class); load(InDefaultPackageWithBasePackageClassesConfiguration.class);
assertThat(capturedOutput).doesNotContain(DEFAULT_SCAN_WARNING); assertThat(output).doesNotContain(DEFAULT_SCAN_WARNING);
} }
@Test @Test
void logWarningInOrgSpringPackage(CapturedOutput capturedOutput) { void logWarningInOrgSpringPackage(CapturedOutput output) {
load(InOrgSpringPackageConfiguration.class); load(InOrgSpringPackageConfiguration.class);
assertThat(capturedOutput).contains(ORGSPRING_SCAN_WARNING); assertThat(output).contains(ORGSPRING_SCAN_WARNING);
} }
@Test @Test
void logWarningIfScanningProblemPackages(CapturedOutput capturedOutput) { void logWarningIfScanningProblemPackages(CapturedOutput output) {
load(InRealButScanningProblemPackages.class); load(InRealButScanningProblemPackages.class);
assertThat(capturedOutput).contains("Your ApplicationContext is unlikely to start due to a " assertThat(output).contains("Your ApplicationContext is unlikely to start due to a "
+ "@ComponentScan of the default package, 'org.springframework'."); + "@ComponentScan of the default package, 'org.springframework'.");
} }

View File

@ -418,54 +418,54 @@ class ConfigFileApplicationListenerTests {
} }
@Test @Test
void profilesAddedToEnvironmentAndViaProperty(CapturedOutput capturedOutput) { void profilesAddedToEnvironmentAndViaProperty(CapturedOutput output) {
// External profile takes precedence over profile added via the environment // External profile takes precedence over profile added via the environment
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other");
this.environment.addActiveProfile("dev"); this.environment.addActiveProfile("dev");
this.initializer.postProcessEnvironment(this.environment, this.application); this.initializer.postProcessEnvironment(this.environment, this.application);
assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); assertThat(this.environment.getActiveProfiles()).contains("dev", "other");
assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile");
validateProfilePreference(capturedOutput, null, "dev", "other"); validateProfilePreference(output, null, "dev", "other");
} }
@Test @Test
void profilesAddedToEnvironmentViaActiveAndIncludeProperty(CapturedOutput capturedOutput) { void profilesAddedToEnvironmentViaActiveAndIncludeProperty(CapturedOutput output) {
// Active profile property takes precedence // Active profile property takes precedence
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev", TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev",
"spring.profiles.include=other"); "spring.profiles.include=other");
this.initializer.postProcessEnvironment(this.environment, this.application); this.initializer.postProcessEnvironment(this.environment, this.application);
assertThat(this.environment.getActiveProfiles()).containsExactly("other", "dev"); assertThat(this.environment.getActiveProfiles()).containsExactly("other", "dev");
assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile");
validateProfilePreference(capturedOutput, null, "other", "dev"); validateProfilePreference(output, null, "other", "dev");
} }
@Test @Test
void profilesAddedViaIncludePropertyAndActivatedViaAnotherPropertySource(CapturedOutput capturedOutput) { void profilesAddedViaIncludePropertyAndActivatedViaAnotherPropertySource(CapturedOutput output) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment,
"spring.profiles.include=dev,simple"); "spring.profiles.include=dev,simple");
this.initializer.postProcessEnvironment(this.environment, this.application); this.initializer.postProcessEnvironment(this.environment, this.application);
assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "simple", "other"); assertThat(this.environment.getActiveProfiles()).containsExactly("dev", "simple", "other");
validateProfilePreference(capturedOutput, "dev", "simple", "other"); validateProfilePreference(output, "dev", "simple", "other");
} }
@Test @Test
void profilesAddedToEnvironmentAndViaPropertyDuplicate(CapturedOutput capturedOutput) { void profilesAddedToEnvironmentAndViaPropertyDuplicate(CapturedOutput output) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev,other"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=dev,other");
this.environment.addActiveProfile("dev"); this.environment.addActiveProfile("dev");
this.initializer.postProcessEnvironment(this.environment, this.application); this.initializer.postProcessEnvironment(this.environment, this.application);
assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); assertThat(this.environment.getActiveProfiles()).contains("dev", "other");
assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromotherpropertiesfile");
validateProfilePreference(capturedOutput, null, "dev", "other"); validateProfilePreference(output, null, "dev", "other");
} }
@Test @Test
void profilesAddedToEnvironmentAndViaPropertyDuplicateEnvironmentWins(CapturedOutput capturedOutput) { void profilesAddedToEnvironmentAndViaPropertyDuplicateEnvironmentWins(CapturedOutput output) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other,dev"); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.profiles.active=other,dev");
this.environment.addActiveProfile("other"); this.environment.addActiveProfile("other");
this.initializer.postProcessEnvironment(this.environment, this.application); this.initializer.postProcessEnvironment(this.environment, this.application);
assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); assertThat(this.environment.getActiveProfiles()).contains("dev", "other");
assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile"); assertThat(this.environment.getProperty("my.property")).isEqualTo("fromdevpropertiesfile");
validateProfilePreference(capturedOutput, null, "other", "dev"); validateProfilePreference(output, null, "other", "dev");
} }
@Test @Test
@ -475,12 +475,11 @@ class ConfigFileApplicationListenerTests {
new ApplicationEnvironmentPreparedEvent(this.application, new String[0], this.environment)); new ApplicationEnvironmentPreparedEvent(this.application, new String[0], this.environment));
} }
private void validateProfilePreference(CapturedOutput capturedOutput, String... profiles) { private void validateProfilePreference(CapturedOutput output, String... profiles) {
ApplicationPreparedEvent event = new ApplicationPreparedEvent(new SpringApplication(), new String[0], ApplicationPreparedEvent event = new ApplicationPreparedEvent(new SpringApplication(), new String[0],
new AnnotationConfigApplicationContext()); new AnnotationConfigApplicationContext());
withDebugLogging(() -> this.initializer.onApplicationEvent(event)); withDebugLogging(() -> this.initializer.onApplicationEvent(event));
String log = capturedOutput.toString(); String log = output.toString();
// First make sure that each profile got processed only once // First make sure that each profile got processed only once
for (String profile : profiles) { for (String profile : profiles) {
String reason = "Wrong number of occurrences for profile '" + profile + "' --> " + log; String reason = "Wrong number of occurrences for profile '" + profile + "' --> " + log;
@ -787,7 +786,7 @@ class ConfigFileApplicationListenerTests {
} }
@Test @Test
void activateProfileFromProfileSpecificProperties(CapturedOutput capturedOutput) { void activateProfileFromProfileSpecificProperties(CapturedOutput output) {
SpringApplication application = new SpringApplication(Config.class); SpringApplication application = new SpringApplication(Config.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
this.context = application.run("--spring.profiles.active=includeprofile"); this.context = application.run("--spring.profiles.active=includeprofile");
@ -797,7 +796,7 @@ class ConfigFileApplicationListenerTests {
assertThat(environment).has(matchingProfile("morespecific")); assertThat(environment).has(matchingProfile("morespecific"));
assertThat(environment).has(matchingProfile("yetmorespecific")); assertThat(environment).has(matchingProfile("yetmorespecific"));
assertThat(environment).doesNotHave(matchingProfile("missing")); assertThat(environment).doesNotHave(matchingProfile("missing"));
assertThat(capturedOutput) assertThat(output)
.contains("The following profiles are active: includeprofile,specific,morespecific,yetmorespecific"); .contains("The following profiles are active: includeprofile,specific,morespecific,yetmorespecific");
} }

View File

@ -67,7 +67,7 @@ class LoggingApplicationListenerIntegrationTests {
} }
@Test @Test
void loggingPerformedDuringChildApplicationStartIsNotLost(CapturedOutput capturedOutput) { void loggingPerformedDuringChildApplicationStartIsNotLost(CapturedOutput output) {
new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).child(Config.class) new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).child(Config.class)
.web(WebApplicationType.NONE).listeners(new ApplicationListener<ApplicationStartingEvent>() { .web(WebApplicationType.NONE).listeners(new ApplicationListener<ApplicationStartingEvent>() {
@ -79,7 +79,7 @@ class LoggingApplicationListenerIntegrationTests {
} }
}).run(); }).run();
assertThat(capturedOutput).contains("Child application starting"); assertThat(output).contains("Child application starting");
} }
@Component @Component

View File

@ -92,7 +92,7 @@ public class LoggingApplicationListenerTests {
private static final String[] NO_ARGS = {}; private static final String[] NO_ARGS = {};
@Rule @Rule
public OutputCaptureRule outputCapture = new OutputCaptureRule(); public OutputCaptureRule output = new OutputCaptureRule();
@Rule @Rule
public final TemporaryFolder temp = new TemporaryFolder(); public final TemporaryFolder temp = new TemporaryFolder();
@ -150,9 +150,9 @@ public class LoggingApplicationListenerTests {
@Test @Test
public void baseConfigLocation() { public void baseConfigLocation() {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.outputCapture.expect(containsString("Hello world")); this.output.expect(containsString("Hello world"));
this.outputCapture.expect(not(containsString("???"))); this.output.expect(not(containsString("???")));
this.outputCapture.expect(containsString("[junit-")); this.output.expect(containsString("[junit-"));
this.logger.info("Hello world", new RuntimeException("Expected")); this.logger.info("Hello world", new RuntimeException("Expected"));
assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse();
} }
@ -162,7 +162,7 @@ public class LoggingApplicationListenerTests {
addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml"); addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml");
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.info("Hello world"); this.logger.info("Hello world");
String output = this.outputCapture.toString().trim(); String output = this.output.toString().trim();
assertThat(output).contains("Hello world").doesNotContain("???").startsWith("null ").endsWith("BOOTBOOT"); assertThat(output).contains("Hello world").doesNotContain("???").startsWith("null ").endsWith("BOOTBOOT");
} }
@ -170,7 +170,7 @@ public class LoggingApplicationListenerTests {
public void overrideConfigDoesNotExist() { public void overrideConfigDoesNotExist() {
addPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); addPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml");
assertThatIllegalStateException().isThrownBy(() -> { assertThatIllegalStateException().isThrownBy(() -> {
this.outputCapture.expect( this.output.expect(
containsString("Logging system failed to initialize using configuration from 'doesnotexist.xml'")); containsString("Logging system failed to initialize using configuration from 'doesnotexist.xml'"));
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
}); });
@ -182,7 +182,7 @@ public class LoggingApplicationListenerTests {
"logging.config=-Djava.util.logging.config.file=\"d:\\home\\site\\wwwroot\\bin\\apache-tomcat-7.0.52\\conf\\logging.properties\""); "logging.config=-Djava.util.logging.config.file=\"d:\\home\\site\\wwwroot\\bin\\apache-tomcat-7.0.52\\conf\\logging.properties\"");
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.info("Hello world"); this.logger.info("Hello world");
String output = this.outputCapture.toString().trim(); String output = this.output.toString().trim();
assertThat(output).contains("Hello world").doesNotContain("???"); assertThat(output).contains("Hello world").doesNotContain("???");
assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse();
} }
@ -192,7 +192,7 @@ public class LoggingApplicationListenerTests {
addPropertiesToEnvironment(this.context, "LOGGING_CONFIG=-Dnop"); addPropertiesToEnvironment(this.context, "LOGGING_CONFIG=-Dnop");
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.info("Hello world"); this.logger.info("Hello world");
String output = this.outputCapture.toString().trim(); String output = this.output.toString().trim();
assertThat(output).contains("Hello world").doesNotContain("???"); assertThat(output).contains("Hello world").doesNotContain("???");
assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse();
} }
@ -201,9 +201,9 @@ public class LoggingApplicationListenerTests {
public void overrideConfigBroken() { public void overrideConfigBroken() {
addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-broken.xml"); addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-broken.xml");
assertThatIllegalStateException().isThrownBy(() -> { assertThatIllegalStateException().isThrownBy(() -> {
this.outputCapture.expect(containsString( this.output.expect(containsString(
"Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'")); "Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'"));
this.outputCapture.expect(containsString("ConsolAppender")); this.output.expect(containsString("ConsolAppender"));
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
}); });
} }
@ -214,9 +214,9 @@ public class LoggingApplicationListenerTests {
"logging.file.name=" + this.logFile); "logging.file.name=" + this.logFile);
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class);
String existingOutput = this.outputCapture.toString(); String existingOutput = this.output.toString();
logger.info("Hello world"); logger.info("Hello world");
String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); String output = this.output.toString().substring(existingOutput.length()).trim();
assertThat(output).startsWith(this.logFile.getAbsolutePath()); assertThat(output).startsWith(this.logFile.getAbsolutePath());
} }
@ -227,9 +227,9 @@ public class LoggingApplicationListenerTests {
"logging.file=" + this.logFile); "logging.file=" + this.logFile);
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class);
String existingOutput = this.outputCapture.toString(); String existingOutput = this.output.toString();
logger.info("Hello world"); logger.info("Hello world");
String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); String output = this.output.toString().substring(existingOutput.length()).trim();
assertThat(output).startsWith(this.logFile.getAbsolutePath()); assertThat(output).startsWith(this.logFile.getAbsolutePath());
} }
@ -260,9 +260,9 @@ public class LoggingApplicationListenerTests {
"logging.file.path=" + this.temp.getRoot()); "logging.file.path=" + this.temp.getRoot());
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class);
String existingOutput = this.outputCapture.toString(); String existingOutput = this.output.toString();
logger.info("Hello world"); logger.info("Hello world");
String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); String output = this.output.toString().substring(existingOutput.length()).trim();
assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath());
} }
@ -272,9 +272,9 @@ public class LoggingApplicationListenerTests {
"logging.path=" + this.temp.getRoot()); "logging.path=" + this.temp.getRoot());
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class);
String existingOutput = this.outputCapture.toString(); String existingOutput = this.output.toString();
logger.info("Hello world"); logger.info("Hello world");
String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); String output = this.output.toString().substring(existingOutput.length()).trim();
assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath());
} }
@ -284,8 +284,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.trace("testattrace"); this.logger.trace("testattrace");
assertThat(this.outputCapture.toString()).contains("testatdebug"); assertThat(this.output.toString()).contains("testatdebug");
assertThat(this.outputCapture.toString()).doesNotContain("testattrace"); assertThat(this.output.toString()).doesNotContain("testattrace");
} }
@Test @Test
@ -294,8 +294,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.loggerContext.getLogger("org.springframework.boot.actuate.endpoint.web").debug("testdebugwebgroup"); this.loggerContext.getLogger("org.springframework.boot.actuate.endpoint.web").debug("testdebugwebgroup");
this.loggerContext.getLogger("org.hibernate.SQL").debug("testdebugsqlgroup"); this.loggerContext.getLogger("org.hibernate.SQL").debug("testdebugsqlgroup");
assertThat(this.outputCapture.toString()).contains("testdebugwebgroup"); assertThat(this.output.toString()).contains("testdebugwebgroup");
assertThat(this.outputCapture.toString()).contains("testdebugsqlgroup"); assertThat(this.output.toString()).contains("testdebugsqlgroup");
} }
@Test @Test
@ -304,8 +304,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.trace("testattrace"); this.logger.trace("testattrace");
assertThat(this.outputCapture.toString()).contains("testatdebug"); assertThat(this.output.toString()).contains("testatdebug");
assertThat(this.outputCapture.toString()).contains("testattrace"); assertThat(this.output.toString()).contains("testattrace");
} }
@Test @Test
@ -323,8 +323,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.trace("testattrace"); this.logger.trace("testattrace");
assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); assertThat(this.output.toString()).doesNotContain("testatdebug");
assertThat(this.outputCapture.toString()).doesNotContain("testattrace"); assertThat(this.output.toString()).doesNotContain("testattrace");
} }
@Test @Test
@ -333,8 +333,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.trace("testattrace"); this.logger.trace("testattrace");
assertThat(this.outputCapture.toString()).contains("testatdebug"); assertThat(this.output.toString()).contains("testatdebug");
assertThat(this.outputCapture.toString()).contains("testattrace"); assertThat(this.output.toString()).contains("testattrace");
} }
@Test @Test
@ -343,8 +343,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.trace("testattrace"); this.logger.trace("testattrace");
assertThat(this.outputCapture.toString()).contains("testatdebug"); assertThat(this.output.toString()).contains("testatdebug");
assertThat(this.outputCapture.toString()).contains("testattrace"); assertThat(this.output.toString()).contains("testattrace");
} }
@Test @Test
@ -353,8 +353,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.trace("testattrace"); this.logger.trace("testattrace");
assertThat(this.outputCapture.toString()).contains("testatdebug"); assertThat(this.output.toString()).contains("testatdebug");
assertThat(this.outputCapture.toString()).contains("testattrace"); assertThat(this.output.toString()).contains("testattrace");
} }
@Test @Test
@ -363,8 +363,8 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.trace("testattrace"); this.logger.trace("testattrace");
assertThat(this.outputCapture.toString()).contains("testatdebug"); assertThat(this.output.toString()).contains("testatdebug");
assertThat(this.outputCapture.toString()).contains("testattrace"); assertThat(this.output.toString()).contains("testattrace");
} }
@Test @Test
@ -381,7 +381,7 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.error("testaterror"); this.logger.error("testaterror");
assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testaterror"); assertThat(this.output.toString()).doesNotContain("testatdebug").doesNotContain("testaterror");
} }
@Test @Test
@ -390,7 +390,7 @@ public class LoggingApplicationListenerTests {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
this.logger.error("testaterror"); this.logger.error("testaterror");
assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testaterror"); assertThat(this.output.toString()).doesNotContain("testatdebug").doesNotContain("testaterror");
} }
@Test @Test
@ -399,7 +399,7 @@ public class LoggingApplicationListenerTests {
addPropertiesToEnvironment(this.context, "debug"); addPropertiesToEnvironment(this.context, "debug");
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); assertThat(this.output.toString()).doesNotContain("testatdebug");
} }
@Test @Test
@ -409,7 +409,7 @@ public class LoggingApplicationListenerTests {
multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[] { "--debug" })); multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[] { "--debug" }));
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); assertThat(this.output.toString()).doesNotContain("testatdebug");
} }
@Test @Test
@ -422,8 +422,8 @@ public class LoggingApplicationListenerTests {
@Test @Test
public void defaultExceptionConversionWord() { public void defaultExceptionConversionWord() {
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.outputCapture.expect(containsString("Hello world")); this.output.expect(containsString("Hello world"));
this.outputCapture.expect(not(containsString("Wrapped by: java.lang.RuntimeException: Wrapper"))); this.output.expect(not(containsString("Wrapped by: java.lang.RuntimeException: Wrapper")));
this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected")));
} }
@ -431,8 +431,8 @@ public class LoggingApplicationListenerTests {
public void overrideExceptionConversionWord() { public void overrideExceptionConversionWord() {
addPropertiesToEnvironment(this.context, "logging.exceptionConversionWord=%rEx"); addPropertiesToEnvironment(this.context, "logging.exceptionConversionWord=%rEx");
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.outputCapture.expect(containsString("Hello world")); this.output.expect(containsString("Hello world"));
this.outputCapture.expect(containsString("Wrapped by: java.lang.RuntimeException: Wrapper")); this.output.expect(containsString("Wrapped by: java.lang.RuntimeException: Wrapper"));
this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected")));
} }
@ -554,7 +554,7 @@ public class LoggingApplicationListenerTests {
propertySources.addLast(new MapPropertySource("test2", Collections.singletonMap("logging.level.root", "WARN"))); propertySources.addLast(new MapPropertySource("test2", Collections.singletonMap("logging.level.root", "WARN")));
this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
this.logger.debug("testatdebug"); this.logger.debug("testatdebug");
assertThat(this.outputCapture.toString()).contains("testatdebug"); assertThat(this.output.toString()).contains("testatdebug");
} }
@Test @Test

View File

@ -504,9 +504,9 @@ class ConfigurationPropertiesTests {
} }
@Test @Test
void loadWhenHasMultiplePropertySourcesPlaceholderConfigurerShouldLogWarning(CapturedOutput capturedOutput) { void loadWhenHasMultiplePropertySourcesPlaceholderConfigurerShouldLogWarning(CapturedOutput output) {
load(MultiplePropertySourcesPlaceholderConfigurerConfiguration.class); load(MultiplePropertySourcesPlaceholderConfigurerConfiguration.class);
assertThat(capturedOutput).contains("Multiple PropertySourcesPlaceholderConfigurer beans registered"); assertThat(output).contains("Multiple PropertySourcesPlaceholderConfigurer beans registered");
} }
@Test @Test

View File

@ -40,10 +40,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
class FailureAnalyzersIntegrationTests { class FailureAnalyzersIntegrationTests {
@Test @Test
void analysisIsPerformed(CapturedOutput capturedOutput) { void analysisIsPerformed(CapturedOutput output) {
assertThatExceptionOfType(Exception.class).isThrownBy( assertThatExceptionOfType(Exception.class).isThrownBy(
() -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run()); () -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run());
assertThat(capturedOutput).contains("APPLICATION FAILED TO START"); assertThat(output).contains("APPLICATION FAILED TO START");
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)

View File

@ -57,11 +57,11 @@ class SpringBootJoranConfiguratorTests {
private Logger logger; private Logger logger;
private CapturedOutput capturedOutput; private CapturedOutput output;
@BeforeEach @BeforeEach
void setup(CapturedOutput capturedOutput) { void setup(CapturedOutput output) {
this.capturedOutput = capturedOutput; this.output = output;
this.environment = new MockEnvironment(); this.environment = new MockEnvironment();
this.initializationContext = new LoggingInitializationContext(this.environment); this.initializationContext = new LoggingInitializationContext(this.environment);
this.configurator = new SpringBootJoranConfigurator(this.initializationContext); this.configurator = new SpringBootJoranConfigurator(this.initializationContext);
@ -81,7 +81,7 @@ class SpringBootJoranConfiguratorTests {
this.environment.setActiveProfiles("production"); this.environment.setActiveProfiles("production");
initialize("production-profile.xml"); initialize("production-profile.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
assertThat(this.capturedOutput).contains("Hello"); assertThat(this.output).contains("Hello");
} }
@Test @Test
@ -89,7 +89,7 @@ class SpringBootJoranConfiguratorTests {
this.environment.setActiveProfiles("production"); this.environment.setActiveProfiles("production");
initialize("multi-profile-names.xml"); initialize("multi-profile-names.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
assertThat(this.capturedOutput).contains("Hello"); assertThat(this.output).contains("Hello");
} }
@Test @Test
@ -97,14 +97,14 @@ class SpringBootJoranConfiguratorTests {
this.environment.setActiveProfiles("test"); this.environment.setActiveProfiles("test");
initialize("multi-profile-names.xml"); initialize("multi-profile-names.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
assertThat(this.capturedOutput).contains("Hello"); assertThat(this.output).contains("Hello");
} }
@Test @Test
void profileNotActive() throws Exception { void profileNotActive() throws Exception {
initialize("production-profile.xml"); initialize("production-profile.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
assertThat(this.capturedOutput).doesNotContain("Hello"); assertThat(this.output).doesNotContain("Hello");
} }
@Test @Test
@ -112,7 +112,7 @@ class SpringBootJoranConfiguratorTests {
this.environment.setActiveProfiles("production"); this.environment.setActiveProfiles("production");
initialize("profile-expression.xml"); initialize("profile-expression.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
assertThat(this.capturedOutput).contains("Hello"); assertThat(this.output).contains("Hello");
} }
@Test @Test
@ -120,7 +120,7 @@ class SpringBootJoranConfiguratorTests {
this.environment.setActiveProfiles("test"); this.environment.setActiveProfiles("test");
initialize("profile-expression.xml"); initialize("profile-expression.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
assertThat(this.capturedOutput).contains("Hello"); assertThat(this.output).contains("Hello");
} }
@Test @Test
@ -128,7 +128,7 @@ class SpringBootJoranConfiguratorTests {
this.environment.setActiveProfiles("development"); this.environment.setActiveProfiles("development");
initialize("profile-expression.xml"); initialize("profile-expression.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
assertThat(this.capturedOutput).doesNotContain("Hello"); assertThat(this.output).doesNotContain("Hello");
} }
@Test @Test
@ -195,10 +195,10 @@ class SpringBootJoranConfiguratorTests {
initialize("nested.xml"); initialize("nested.xml");
this.logger.trace("Hello"); this.logger.trace("Hello");
if (expected) { if (expected) {
assertThat(this.capturedOutput).contains("Hello"); assertThat(this.output).contains("Hello");
} }
else { else {
assertThat(this.capturedOutput).doesNotContain("Hello"); assertThat(this.output).doesNotContain("Hello");
} }
} }

View File

@ -160,8 +160,7 @@ class SslConnectorCustomizerTests {
} }
@Test @Test
void customizeWhenSslStoreProviderPresentShouldIgnorePasswordFromSsl(CapturedOutput capturedOutput) void customizeWhenSslStoreProviderPresentShouldIgnorePasswordFromSsl(CapturedOutput output) throws Exception {
throws Exception {
System.setProperty("javax.net.ssl.trustStorePassword", "trustStoreSecret"); System.setProperty("javax.net.ssl.trustStorePassword", "trustStoreSecret");
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
ssl.setKeyPassword("password"); ssl.setKeyPassword("password");
@ -174,7 +173,7 @@ class SslConnectorCustomizerTests {
customizer.customize(connector); customizer.customize(connector);
this.tomcat.start(); this.tomcat.start();
assertThat(connector.getState()).isEqualTo(LifecycleState.STARTED); assertThat(connector.getState()).isEqualTo(LifecycleState.STARTED);
assertThat(capturedOutput).doesNotContain("Password verification failed"); assertThat(output).doesNotContain("Password verification failed");
} }
@Test @Test

View File

@ -328,9 +328,9 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory
} }
@Test @Test
void startupFailureDoesNotResultInUnstoppedThreadsBeingReported(CapturedOutput capturedOutput) throws IOException { void startupFailureDoesNotResultInUnstoppedThreadsBeingReported(CapturedOutput output) throws IOException {
super.portClashOfPrimaryConnectorResultsInPortInUseException(); super.portClashOfPrimaryConnectorResultsInPortInUseException();
assertThat(capturedOutput).doesNotContain("appears to have started a thread named [main]"); assertThat(output).doesNotContain("appears to have started a thread named [main]");
} }
@Test @Test

View File

@ -419,9 +419,9 @@ class ServletWebServerApplicationContextTests {
} }
@Test @Test
void servletRequestCanBeInjectedEarly(CapturedOutput capturedOutput) throws Exception { void servletRequestCanBeInjectedEarly(CapturedOutput output) throws Exception {
// gh-14990 // gh-14990
int initialOutputLength = capturedOutput.length(); int initialOutputLength = output.length();
addWebServerFactoryBean(); addWebServerFactoryBean();
RootBeanDefinition beanDefinition = new RootBeanDefinition(WithAutowiredServletRequest.class); RootBeanDefinition beanDefinition = new RootBeanDefinition(WithAutowiredServletRequest.class);
beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
@ -431,8 +431,7 @@ class ServletWebServerApplicationContextTests {
assertThat(bean.getRequest()).isNotNull(); assertThat(bean.getRequest()).isNotNull();
}); });
this.context.refresh(); this.context.refresh();
String output = capturedOutput.toString().substring(initialOutputLength); assertThat(output.toString().substring(initialOutputLength)).doesNotContain("Replacing scope");
assertThat(output).doesNotContain("Replacing scope");
} }
@Test @Test

View File

@ -167,7 +167,7 @@ public abstract class AbstractServletWebServerFactoryTests {
} }
@Test @Test
void startCalledTwice(CapturedOutput capturedOutput) throws Exception { void startCalledTwice(CapturedOutput output) throws Exception {
AbstractServletWebServerFactory factory = getFactory(); AbstractServletWebServerFactory factory = getFactory();
this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer = factory.getWebServer(exampleServletRegistration());
this.webServer.start(); this.webServer.start();
@ -175,7 +175,7 @@ public abstract class AbstractServletWebServerFactoryTests {
this.webServer.start(); this.webServer.start();
assertThat(this.webServer.getPort()).isEqualTo(port); assertThat(this.webServer.getPort()).isEqualTo(port);
assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World");
assertThat(capturedOutput).containsOnlyOnce("started on port"); assertThat(output).containsOnlyOnce("started on port");
} }
@Test @Test
@ -264,12 +264,12 @@ public abstract class AbstractServletWebServerFactoryTests {
} }
@Test @Test
void contextPathIsLoggedOnStartup(CapturedOutput capturedOutput) { void contextPathIsLoggedOnStartup(CapturedOutput output) {
AbstractServletWebServerFactory factory = getFactory(); AbstractServletWebServerFactory factory = getFactory();
factory.setContextPath("/custom"); factory.setContextPath("/custom");
this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer = factory.getWebServer(exampleServletRegistration());
this.webServer.start(); this.webServer.start();
assertThat(capturedOutput).containsOnlyOnce("with context path '/custom'"); assertThat(output).containsOnlyOnce("with context path '/custom'");
} }
@Test @Test

View File

@ -125,7 +125,7 @@ class ErrorPageFilterTests {
} }
@Test @Test
void responseCommittedWhenFromClientAbortException(CapturedOutput capturedOutput) throws Exception { void responseCommittedWhenFromClientAbortException(CapturedOutput output) throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.response.setCommitted(true); this.response.setCommitted(true);
this.chain = new TestFilterChain((request, response, chain) -> { this.chain = new TestFilterChain((request, response, chain) -> {
@ -134,7 +134,7 @@ class ErrorPageFilterTests {
}); });
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.response.isCommitted()).isTrue(); assertThat(this.response.isCommitted()).isTrue();
assertThat(capturedOutput).doesNotContain("Cannot forward"); assertThat(output).doesNotContain("Cannot forward");
} }
@Test @Test
@ -342,7 +342,7 @@ class ErrorPageFilterTests {
} }
@Test @Test
void errorMessageForRequestWithoutPathInfo(CapturedOutput capturedOutput) throws IOException, ServletException { void errorMessageForRequestWithoutPathInfo(CapturedOutput output) throws IOException, ServletException {
this.request.setServletPath("/test"); this.request.setServletPath("/test");
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.chain = new TestFilterChain((request, response, chain) -> { this.chain = new TestFilterChain((request, response, chain) -> {
@ -350,11 +350,11 @@ class ErrorPageFilterTests {
throw new RuntimeException(); throw new RuntimeException();
}); });
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(capturedOutput).contains("request [/test]"); assertThat(output).contains("request [/test]");
} }
@Test @Test
void errorMessageForRequestWithPathInfo(CapturedOutput capturedOutput) throws IOException, ServletException { void errorMessageForRequestWithPathInfo(CapturedOutput output) throws IOException, ServletException {
this.request.setServletPath("/test"); this.request.setServletPath("/test");
this.request.setPathInfo("/alpha"); this.request.setPathInfo("/alpha");
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
@ -363,7 +363,7 @@ class ErrorPageFilterTests {
throw new RuntimeException(); throw new RuntimeException();
}); });
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(capturedOutput).contains("request [/test/alpha]"); assertThat(output).contains("request [/test/alpha]");
} }
@Test @Test

View File

@ -61,8 +61,8 @@ class SpringBootServletInitializerTests {
private SpringApplication application; private SpringApplication application;
@AfterEach @AfterEach
void verifyLoggingOutput(CapturedOutput capturedOutput) { void verifyLoggingOutput(CapturedOutput output) {
assertThat(capturedOutput).doesNotContain(StandardServletEnvironment.class.getSimpleName()); assertThat(output).doesNotContain(StandardServletEnvironment.class.getSimpleName());
} }
@Test @Test

View File

@ -39,10 +39,10 @@ class SampleActiveMqTests {
private Producer producer; private Producer producer;
@Test @Test
void sendSimpleMessage(CapturedOutput capturedOutput) throws InterruptedException { void sendSimpleMessage(CapturedOutput output) throws InterruptedException {
this.producer.send("Test message"); this.producer.send("Test message");
Thread.sleep(1000L); Thread.sleep(1000L);
assertThat(capturedOutput).contains("Test message"); assertThat(output).contains("Test message");
} }
} }

View File

@ -52,9 +52,9 @@ class SampleActuatorLog4J2ApplicationTests {
private MockMvc mvc; private MockMvc mvc;
@Test @Test
void testLogger(CapturedOutput capturedOutput) { void testLogger(CapturedOutput output) {
logger.info("Hello World"); logger.info("Hello World");
assertThat(capturedOutput).contains("Hello World"); assertThat(output).contains("Hello World");
} }
@Test @Test

View File

@ -53,15 +53,15 @@ class SampleAopApplicationTests {
} }
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) throws Exception { void testDefaultSettings(CapturedOutput output) throws Exception {
SampleAopApplication.main(new String[0]); SampleAopApplication.main(new String[0]);
assertThat(capturedOutput).contains("Hello Phil"); assertThat(output).contains("Hello Phil");
} }
@Test @Test
void testCommandLineOverrides(CapturedOutput capturedOutput) throws Exception { void testCommandLineOverrides(CapturedOutput output) throws Exception {
SampleAopApplication.main(new String[] { "--name=Gordon" }); SampleAopApplication.main(new String[] { "--name=Gordon" });
assertThat(capturedOutput).contains("Hello Gordon"); assertThat(output).contains("Hello Gordon");
} }
} }

View File

@ -29,9 +29,9 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleBatchApplicationTests { class SampleBatchApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) { void testDefaultSettings(CapturedOutput output) {
assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
assertThat(capturedOutput).contains("completed with the following parameters"); assertThat(output).contains("completed with the following parameters");
} }
} }

View File

@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleCouchbaseApplicationTests { class SampleCouchbaseApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) { void testDefaultSettings(CapturedOutput output) {
try { try {
new SpringApplicationBuilder(SampleCouchbaseApplication.class).run("--server.port=0"); new SpringApplicationBuilder(SampleCouchbaseApplication.class).run("--server.port=0");
} }
@ -40,7 +40,7 @@ class SampleCouchbaseApplicationTests {
return; return;
} }
} }
assertThat(capturedOutput).contains("firstName='Alice', lastName='Smith'"); assertThat(output).contains("firstName='Alice', lastName='Smith'");
} }
private boolean serverNotRunning(RuntimeException ex) { private boolean serverNotRunning(RuntimeException ex) {

View File

@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleElasticsearchApplicationTests { class SampleElasticsearchApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) { void testDefaultSettings(CapturedOutput output) {
try { try {
new SpringApplicationBuilder(SampleElasticsearchApplication.class).run(); new SpringApplicationBuilder(SampleElasticsearchApplication.class).run();
} }
@ -46,7 +46,7 @@ class SampleElasticsearchApplicationTests {
} }
throw ex; throw ex;
} }
assertThat(capturedOutput).contains("firstName='Alice', lastName='Smith'"); assertThat(output).contains("firstName='Alice', lastName='Smith'");
} }
private boolean elasticsearchRunning(Exception ex) { private boolean elasticsearchRunning(Exception ex) {

View File

@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleNeo4jApplicationTests { class SampleNeo4jApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) { void testDefaultSettings(CapturedOutput output) {
try { try {
SampleNeo4jApplication.main(new String[0]); SampleNeo4jApplication.main(new String[0]);
} }
@ -43,7 +43,7 @@ class SampleNeo4jApplicationTests {
return; return;
} }
} }
assertThat(capturedOutput).contains("firstName='Alice', lastName='Smith'"); assertThat(output).contains("firstName='Alice', lastName='Smith'");
} }
private boolean neo4jServerRunning(Throwable ex) { private boolean neo4jServerRunning(Throwable ex) {

View File

@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleRedisApplicationTests { class SampleRedisApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) { void testDefaultSettings(CapturedOutput output) {
try { try {
SampleRedisApplication.main(new String[0]); SampleRedisApplication.main(new String[0]);
} }
@ -43,7 +43,7 @@ class SampleRedisApplicationTests {
return; return;
} }
} }
assertThat(capturedOutput).contains("Found key spring.boot.redis.test"); assertThat(output).contains("Found key spring.boot.redis.test");
} }
private boolean redisServerRunning(Throwable ex) { private boolean redisServerRunning(Throwable ex) {

View File

@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleSolrApplicationTests { class SampleSolrApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) throws Exception { void testDefaultSettings(CapturedOutput output) throws Exception {
try { try {
SampleSolrApplication.main(new String[0]); SampleSolrApplication.main(new String[0]);
} }
@ -38,7 +38,7 @@ class SampleSolrApplicationTests {
return; return;
} }
} }
assertThat(capturedOutput).contains("name=Sony Playstation"); assertThat(output).contains("name=Sony Playstation");
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")

View File

@ -33,9 +33,9 @@ class SampleJooqApplicationTests {
private static final String[] NO_ARGS = {}; private static final String[] NO_ARGS = {};
@Test @Test
void outputResults(CapturedOutput capturedOutput) { void outputResults(CapturedOutput output) {
SampleJooqApplication.main(NO_ARGS); SampleJooqApplication.main(NO_ARGS);
assertThat(capturedOutput).contains("jOOQ Fetch 1 Greg Turnquest").contains("jOOQ Fetch 2 Craig Walls") assertThat(output).contains("jOOQ Fetch 1 Greg Turnquest").contains("jOOQ Fetch 2 Craig Walls")
.contains("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " .contains("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, "
+ "Spring Boot in Action : Craig Walls]"); + "Spring Boot in Action : Craig Walls]");
} }

View File

@ -34,9 +34,9 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleAtomikosApplicationTests { class SampleAtomikosApplicationTests {
@Test @Test
void testTransactionRollback(CapturedOutput capturedOutput) throws Exception { void testTransactionRollback(CapturedOutput output) throws Exception {
SampleAtomikosApplication.main(new String[] {}); SampleAtomikosApplication.main(new String[] {});
assertThat(capturedOutput.toString()).has(substring(1, "---->")).has(substring(1, "----> josh")) assertThat(output.toString()).has(substring(1, "---->")).has(substring(1, "----> josh"))
.has(substring(2, "Count is 1")).has(substring(1, "Simulated error")); .has(substring(2, "Count is 1")).has(substring(1, "Simulated error"));
} }

View File

@ -37,9 +37,9 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleBitronixApplicationTests { class SampleBitronixApplicationTests {
@Test @Test
void testTransactionRollback(CapturedOutput capturedOutput) throws Exception { void testTransactionRollback(CapturedOutput output) throws Exception {
SampleBitronixApplication.main(new String[] {}); SampleBitronixApplication.main(new String[] {});
assertThat(capturedOutput.toString()).has(substring(1, "---->")).has(substring(1, "----> josh")) assertThat(output.toString()).has(substring(1, "---->")).has(substring(1, "----> josh"))
.has(substring(2, "Count is 1")).has(substring(1, "Simulated error")); .has(substring(2, "Count is 1")).has(substring(1, "Simulated error"));
} }

View File

@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleLiquibaseApplicationTests { class SampleLiquibaseApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) throws Exception { void testDefaultSettings(CapturedOutput output) throws Exception {
try { try {
SampleLiquibaseApplication.main(new String[] { "--server.port=0" }); SampleLiquibaseApplication.main(new String[] { "--server.port=0" });
} }
@ -40,7 +40,7 @@ class SampleLiquibaseApplicationTests {
return; return;
} }
} }
assertThat(capturedOutput).contains("Successfully acquired change log lock") assertThat(output).contains("Successfully acquired change log lock")
.contains("Creating database history " + "table with name: PUBLIC.DATABASECHANGELOG") .contains("Creating database history " + "table with name: PUBLIC.DATABASECHANGELOG")
.contains("Table person created") .contains("Table person created")
.contains("ChangeSet classpath:/db/" + "changelog/db.changelog-master.yaml::1::" .contains("ChangeSet classpath:/db/" + "changelog/db.changelog-master.yaml::1::"

View File

@ -28,15 +28,15 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleLogbackApplicationTests { class SampleLogbackApplicationTests {
@Test @Test
void testLoadedCustomLogbackConfig(CapturedOutput capturedOutput) throws Exception { void testLoadedCustomLogbackConfig(CapturedOutput output) throws Exception {
SampleLogbackApplication.main(new String[0]); SampleLogbackApplication.main(new String[0]);
assertThat(capturedOutput).contains("Sample Debug Message").doesNotContain("Sample Trace Message"); assertThat(output).contains("Sample Debug Message").doesNotContain("Sample Trace Message");
} }
@Test @Test
void testProfile(CapturedOutput capturedOutput) throws Exception { void testProfile(CapturedOutput output) throws Exception {
SampleLogbackApplication.main(new String[] { "--spring.profiles.active=staging" }); SampleLogbackApplication.main(new String[] { "--spring.profiles.active=staging" });
assertThat(capturedOutput).contains("Sample Debug Message").contains("Sample Trace Message"); assertThat(output).contains("Sample Debug Message").contains("Sample Trace Message");
} }
} }

View File

@ -47,20 +47,20 @@ class SampleProfileApplicationTests {
} }
@Test @Test
void testDefaultProfile(CapturedOutput capturedOutput) { void testDefaultProfile(CapturedOutput output) {
SampleProfileApplication.main(new String[0]); SampleProfileApplication.main(new String[0]);
assertThat(capturedOutput).contains("Hello Phil"); assertThat(output).contains("Hello Phil");
} }
@Test @Test
void testGoodbyeProfile(CapturedOutput capturedOutput) { void testGoodbyeProfile(CapturedOutput output) {
System.setProperty("spring.profiles.active", "goodbye"); System.setProperty("spring.profiles.active", "goodbye");
SampleProfileApplication.main(new String[0]); SampleProfileApplication.main(new String[0]);
assertThat(capturedOutput).contains("Goodbye Everyone"); assertThat(output).contains("Goodbye Everyone");
} }
@Test @Test
void testGenericProfile(CapturedOutput capturedOutput) { void testGenericProfile(CapturedOutput output) {
/* /*
* This is a profile that requires a new environment property, and one which is * This is a profile that requires a new environment property, and one which is
* only overridden in the current working directory. That file also only contains * only overridden in the current working directory. That file also only contains
@ -69,13 +69,13 @@ class SampleProfileApplicationTests {
*/ */
System.setProperty("spring.profiles.active", "generic"); System.setProperty("spring.profiles.active", "generic");
SampleProfileApplication.main(new String[0]); SampleProfileApplication.main(new String[0]);
assertThat(capturedOutput).contains("Bonjour Phil"); assertThat(output).contains("Bonjour Phil");
} }
@Test @Test
void testGoodbyeProfileFromCommandline(CapturedOutput capturedOutput) { void testGoodbyeProfileFromCommandline(CapturedOutput output) {
SampleProfileApplication.main(new String[] { "--spring.profiles.active=goodbye" }); SampleProfileApplication.main(new String[] { "--spring.profiles.active=goodbye" });
assertThat(capturedOutput).contains("Goodbye Everyone"); assertThat(output).contains("Goodbye Everyone");
} }
} }

View File

@ -35,13 +35,13 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleQuartzApplicationTests { class SampleQuartzApplicationTests {
@Test @Test
void quartzJobIsTriggered(CapturedOutput capturedOutput) throws InterruptedException { void quartzJobIsTriggered(CapturedOutput output) throws InterruptedException {
try (ConfigurableApplicationContext context = SpringApplication.run(SampleQuartzApplication.class)) { try (ConfigurableApplicationContext context = SpringApplication.run(SampleQuartzApplication.class)) {
long end = System.currentTimeMillis() + 5000; long end = System.currentTimeMillis() + 5000;
while ((!capturedOutput.toString().contains("Hello World!")) && System.currentTimeMillis() < end) { while ((!output.toString().contains("Hello World!")) && System.currentTimeMillis() < end) {
Thread.sleep(100); Thread.sleep(100);
} }
assertThat(capturedOutput).contains("Hello World!"); assertThat(output).contains("Hello World!");
} }
} }

View File

@ -53,15 +53,15 @@ class SampleSimpleApplicationTests {
} }
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) { void testDefaultSettings(CapturedOutput output) {
SampleSimpleApplication.main(new String[0]); SampleSimpleApplication.main(new String[0]);
assertThat(capturedOutput).contains("Hello Phil"); assertThat(output).contains("Hello Phil");
} }
@Test @Test
void testCommandLineOverrides(CapturedOutput capturedOutput) { void testCommandLineOverrides(CapturedOutput output) {
SampleSimpleApplication.main(new String[] { "--name=Gordon", "--duration=1m" }); SampleSimpleApplication.main(new String[] { "--name=Gordon", "--duration=1m" });
assertThat(capturedOutput).contains("Hello Gordon for 60 seconds"); assertThat(output).contains("Hello Gordon for 60 seconds");
} }
} }

View File

@ -49,7 +49,7 @@ class SampleWsApplicationTests {
} }
@Test @Test
void testSendingHolidayRequest(CapturedOutput capturedOutput) { void testSendingHolidayRequest(CapturedOutput output) {
final String request = "<hr:HolidayRequest xmlns:hr=\"https://company.example.com/hr/schemas\">" final String request = "<hr:HolidayRequest xmlns:hr=\"https://company.example.com/hr/schemas\">"
+ " <hr:Holiday>" + " <hr:StartDate>2013-10-20</hr:StartDate>" + " <hr:Holiday>" + " <hr:StartDate>2013-10-20</hr:StartDate>"
+ " <hr:EndDate>2013-11-22</hr:EndDate>" + " </hr:Holiday>" + " <hr:Employee>" + " <hr:EndDate>2013-11-22</hr:EndDate>" + " </hr:Holiday>" + " <hr:Employee>"
@ -58,7 +58,7 @@ class SampleWsApplicationTests {
StreamSource source = new StreamSource(new StringReader(request)); StreamSource source = new StreamSource(new StringReader(request));
StreamResult result = new StreamResult(System.out); StreamResult result = new StreamResult(System.out);
this.webServiceTemplate.sendSourceAndReceiveToResult(source, result); this.webServiceTemplate.sendSourceAndReceiveToResult(source, result);
assertThat(capturedOutput).contains("Booking holiday for"); assertThat(output).contains("Booking holiday for");
} }
} }

View File

@ -28,9 +28,9 @@ import static org.assertj.core.api.Assertions.assertThat;
class SampleSpringXmlApplicationTests { class SampleSpringXmlApplicationTests {
@Test @Test
void testDefaultSettings(CapturedOutput capturedOutput) throws Exception { void testDefaultSettings(CapturedOutput output) throws Exception {
SampleSpringXmlApplication.main(new String[0]); SampleSpringXmlApplication.main(new String[0]);
assertThat(capturedOutput).contains("Hello World"); assertThat(output).contains("Hello World");
} }
} }