Repackage output capture and always use extension declaratively

Closes gh-17029
This commit is contained in:
Andy Wilkinson
2019-05-31 10:03:02 +01:00
parent d11d5ceb29
commit 0644a79401
69 changed files with 584 additions and 657 deletions

View File

@@ -21,7 +21,7 @@ import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.CollectorRegistry;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementContextAutoConfiguration;
import org.springframework.boot.actuate.metrics.export.prometheus.PrometheusPushGatewayManager;
@@ -29,8 +29,8 @@ import org.springframework.boot.actuate.metrics.export.prometheus.PrometheusScra
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@@ -43,11 +43,9 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Andy Wilkinson
*/
@ExtendWith(OutputCaptureExtension.class)
public class PrometheusMetricsExportAutoConfigurationTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations
.of(PrometheusMetricsExportAutoConfiguration.class));
@@ -152,14 +150,14 @@ public class PrometheusMetricsExportAutoConfigurationTests {
}
@Test
public void withPushGatewayEnabled() {
public void withPushGatewayEnabled(CapturedOutput capturedOutput) {
this.contextRunner
.withConfiguration(
AutoConfigurations.of(ManagementContextAutoConfiguration.class))
.withPropertyValues(
"management.metrics.export.prometheus.pushgateway.enabled=true")
.withUserConfiguration(BaseConfiguration.class).run((context) -> {
assertThat(this.output.toString())
assertThat(capturedOutput)
.doesNotContain("Invalid PushGateway base url");
hasGatewayURL(context, "http://localhost:9091/metrics/job/");
});
@@ -167,7 +165,7 @@ public class PrometheusMetricsExportAutoConfigurationTests {
@Test
@Deprecated
public void withCustomLegacyPushGatewayURL() {
public void withCustomLegacyPushGatewayURL(CapturedOutput capturedOutput) {
this.contextRunner
.withConfiguration(
AutoConfigurations.of(ManagementContextAutoConfiguration.class))
@@ -175,8 +173,7 @@ public class PrometheusMetricsExportAutoConfigurationTests {
"management.metrics.export.prometheus.pushgateway.enabled=true",
"management.metrics.export.prometheus.pushgateway.base-url=localhost:9090")
.withUserConfiguration(BaseConfiguration.class).run((context) -> {
assertThat(this.output.toString())
.contains("Invalid PushGateway base url")
assertThat(capturedOutput).contains("Invalid PushGateway base url")
.contains("localhost:9090");
hasGatewayURL(context, "http://localhost:9090/metrics/job/");
});

View File

@@ -20,7 +20,7 @@ import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.HistogramSnapshot;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun;
import org.springframework.boot.actuate.metrics.web.client.DefaultRestTemplateExchangeTagsProvider;
@@ -29,8 +29,8 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.client.MockRestServiceServer;
@@ -47,6 +47,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
* @author Jon Schneider
* @author Raheela Aslam
*/
@ExtendWith(OutputCaptureExtension.class)
public class RestTemplateMetricsConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
@@ -54,9 +55,6 @@ public class RestTemplateMetricsConfigurationTests {
.withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class,
HttpClientMetricsAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void restTemplateCreatedWithBuilderIsInstrumented() {
this.contextRunner.run((context) -> {
@@ -78,26 +76,26 @@ public class RestTemplateMetricsConfigurationTests {
}
@Test
public void afterMaxUrisReachedFurtherUrisAreDenied() {
public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) {
this.contextRunner
.withPropertyValues("management.metrics.web.client.max-uri-tags=2")
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(2);
assertThat(this.output.toString()).contains(
assertThat(capturedOutput).contains(
"Reached the maximum number of URI tags for 'http.client.requests'.")
.contains("Are you using 'uriVariables'?");
});
}
@Test
public void shouldNotDenyNorLogIfMaxUrisIsNotReached() {
public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) {
this.contextRunner
.withPropertyValues("management.metrics.web.client.max-uri-tags=5")
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(3);
assertThat(this.output.toString()).doesNotContain(
assertThat(capturedOutput).doesNotContain(
"Reached the maximum number of URI tags for 'http.client.requests'.")
.doesNotContain("Are you using 'uriVariables'?");
});

View File

@@ -22,7 +22,7 @@ import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.HistogramSnapshot;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.core.publisher.Mono;
import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun;
@@ -31,8 +31,8 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@@ -51,6 +51,7 @@ import static org.mockito.Mockito.mock;
* @author Brian Clozel
* @author Stephane Nicoll
*/
@ExtendWith(OutputCaptureExtension.class)
public class WebClientMetricsConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
@@ -58,9 +59,6 @@ public class WebClientMetricsConfigurationTests {
.withConfiguration(AutoConfigurations.of(WebClientAutoConfiguration.class,
HttpClientMetricsAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void webClientCreatedWithBuilderIsInstrumented() {
this.contextRunner.run((context) -> {
@@ -79,26 +77,26 @@ public class WebClientMetricsConfigurationTests {
}
@Test
public void afterMaxUrisReachedFurtherUrisAreDenied() {
public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) {
this.contextRunner
.withPropertyValues("management.metrics.web.client.max-uri-tags=2")
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(2);
assertThat(this.output.toString()).contains(
assertThat(capturedOutput).contains(
"Reached the maximum number of URI tags for 'http.client.requests'.")
.contains("Are you using 'uriVariables'?");
});
}
@Test
public void shouldNotDenyNorLogIfMaxUrisIsNotReached() {
public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) {
this.contextRunner
.withPropertyValues("management.metrics.web.client.max-uri-tags=5")
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.client.requests").meters()).hasSize(3);
assertThat(this.output.toString()).doesNotContain(
assertThat(capturedOutput).doesNotContain(
"Reached the maximum number of URI tags for 'http.client.requests'.")
.doesNotContain("Are you using 'uriVariables'?");
});

View File

@@ -18,7 +18,7 @@ package org.springframework.boot.actuate.autoconfigure.metrics.web.reactive;
import io.micrometer.core.instrument.MeterRegistry;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun;
import org.springframework.boot.actuate.autoconfigure.metrics.web.TestController;
@@ -29,8 +29,8 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
import org.springframework.boot.test.context.assertj.AssertableReactiveWebApplicationContext;
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.web.reactive.server.WebTestClient;
@@ -44,15 +44,13 @@ import static org.mockito.Mockito.mock;
* @author Brian Clozel
* @author Dmytro Nosan
*/
@ExtendWith(OutputCaptureExtension.class)
public class WebFluxMetricsAutoConfigurationTests {
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.with(MetricsRun.simple()).withConfiguration(
AutoConfigurations.of(WebFluxMetricsAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void shouldProvideWebFluxMetricsBeans() {
this.contextRunner.run((context) -> {
@@ -69,7 +67,7 @@ public class WebFluxMetricsAutoConfigurationTests {
}
@Test
public void afterMaxUrisReachedFurtherUrisAreDenied() {
public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) {
this.contextRunner
.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class))
.withUserConfiguration(TestController.class)
@@ -77,14 +75,14 @@ public class WebFluxMetricsAutoConfigurationTests {
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(2);
assertThat(this.output.toString())
assertThat(capturedOutput)
.contains("Reached the maximum number of URI tags "
+ "for 'http.server.requests'");
});
}
@Test
public void shouldNotDenyNorLogIfMaxUrisIsNotReached() {
public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) {
this.contextRunner
.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class))
.withUserConfiguration(TestController.class)
@@ -92,7 +90,7 @@ public class WebFluxMetricsAutoConfigurationTests {
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(3);
assertThat(this.output.toString()).doesNotContain(
assertThat(capturedOutput).doesNotContain(
"Reached the maximum number of URI tags for 'http.server.requests'");
});
}

View File

@@ -29,7 +29,7 @@ import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.HistogramSnapshot;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun;
@@ -42,8 +42,8 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -63,15 +63,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Dmytro Nosan
* @author Tadaya Tsuyukubo
*/
@ExtendWith(OutputCaptureExtension.class)
public class WebMvcMetricsAutoConfigurationTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.with(MetricsRun.simple()).withConfiguration(
AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void backsOffWhenMeterRegistryIsMissing() {
new WebApplicationContextRunner()
@@ -112,7 +110,7 @@ public class WebMvcMetricsAutoConfigurationTests {
}
@Test
public void afterMaxUrisReachedFurtherUrisAreDenied() {
public void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput capturedOutput) {
this.contextRunner.withUserConfiguration(TestController.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
WebMvcAutoConfiguration.class))
@@ -120,14 +118,14 @@ public class WebMvcMetricsAutoConfigurationTests {
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(2);
assertThat(this.output.toString())
assertThat(capturedOutput)
.contains("Reached the maximum number of URI tags "
+ "for 'http.server.requests'");
});
}
@Test
public void shouldNotDenyNorLogIfMaxUrisIsNotReached() {
public void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput capturedOutput) {
this.contextRunner.withUserConfiguration(TestController.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
WebMvcAutoConfiguration.class))
@@ -135,7 +133,7 @@ public class WebMvcMetricsAutoConfigurationTests {
.run((context) -> {
MeterRegistry registry = getInitializedMeterRegistry(context);
assertThat(registry.get("http.server.requests").meters()).hasSize(3);
assertThat(this.output.toString())
assertThat(capturedOutput)
.doesNotContain("Reached the maximum number of URI tags "
+ "for 'http.server.requests'");
});

View File

@@ -19,7 +19,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointAutoConfiguration;
@@ -27,8 +27,8 @@ import org.springframework.boot.actuate.autoconfigure.web.servlet.ServletManagem
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
@@ -39,13 +39,12 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Madhura Bhave
* @author Andy Wilkinson
*/
@ExtendWith(OutputCaptureExtension.class)
public class ManagementContextAutoConfigurationTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void childManagementContextShouldStartForEmbeddedServer() {
public void childManagementContextShouldStartForEmbeddedServer(
CapturedOutput capturedOutput) {
WebApplicationContextRunner contextRunner = new WebApplicationContextRunner(
AnnotationConfigServletWebServerApplicationContext::new)
.withConfiguration(AutoConfigurations.of(
@@ -54,12 +53,12 @@ public class ManagementContextAutoConfigurationTests {
ServletManagementContextAutoConfiguration.class,
WebEndpointAutoConfiguration.class,
EndpointAutoConfiguration.class));
contextRunner.withPropertyValues("server.port=0", "management.server.port=0").run(
(context) -> assertThat(tomcatStartedOccurencesIn(this.output.toString()))
contextRunner.withPropertyValues("server.port=0", "management.server.port=0")
.run((context) -> assertThat(tomcatStartedOccurencesIn(capturedOutput))
.isEqualTo(2));
}
private int tomcatStartedOccurencesIn(String output) {
private int tomcatStartedOccurencesIn(CharSequence output) {
int matches = 0;
Matcher matcher = Pattern.compile("Tomcat started on port").matcher(output);
while (matcher.find()) {

View File

@@ -17,10 +17,10 @@
package org.springframework.boot.actuate.endpoint;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -30,11 +30,9 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Phillip Webb
*/
@ExtendWith(OutputCaptureExtension.class)
public class EndpointIdTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void ofWhenNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of(null))
@@ -88,10 +86,10 @@ public class EndpointIdTests {
}
@Test
public void ofWhenContainsDeprecatedCharsLogsWarning() {
public void ofWhenContainsDeprecatedCharsLogsWarning(CapturedOutput capturedOutput) {
EndpointId.resetLoggedWarnings();
EndpointId.of("foo-bar");
assertThat(this.output.toString()).contains(
assertThat(capturedOutput.toString()).contains(
"Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format");
}

View File

@@ -79,6 +79,7 @@ public class MongoProperties {
/**
* Login user of the mongo server. Cannot be set with URI.
*/
private String username;
/**

View File

@@ -20,12 +20,12 @@ import java.io.File;
import java.io.StringWriter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.testsupport.BuildOutput;
import static org.assertj.core.api.Assertions.assertThat;
@@ -36,11 +36,9 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Andy Wilkinson
* @author Kazuki Shimizu
*/
@ExtendWith(OutputCaptureExtension.class)
public class FreeMarkerAutoConfigurationTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
private final BuildOutput buildOutput = new BuildOutput(getClass());
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
@@ -62,33 +60,33 @@ public class FreeMarkerAutoConfigurationTests {
}
@Test
public void nonExistentTemplateLocation() {
public void nonExistentTemplateLocation(CapturedOutput capturedOutput) {
this.contextRunner
.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/also-does-not-exist")
.run((context) -> assertThat(this.output)
.run((context) -> assertThat(capturedOutput)
.contains("Cannot find template location"));
}
@Test
public void emptyTemplateLocation() {
public void emptyTemplateLocation(CapturedOutput capturedOutput) {
File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(),
"empty-templates/empty-directory");
emptyDirectory.mkdirs();
this.contextRunner
.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/empty-templates/empty-directory/")
.run((context) -> assertThat(this.output.toString())
.run((context) -> assertThat(capturedOutput)
.doesNotContain("Cannot find template location"));
}
@Test
public void nonExistentLocationAndEmptyLocation() {
public void nonExistentLocationAndEmptyLocation(CapturedOutput capturedOutput) {
new File(this.buildOutput.getTestResourcesLocation(),
"empty-templates/empty-directory").mkdirs();
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/")
.run((context) -> assertThat(this.output.toString())
.run((context) -> assertThat(capturedOutput)
.doesNotContain("Cannot find template location"));
}

View File

@@ -21,14 +21,11 @@ import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import org.influxdb.InfluxDB;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import retrofit2.Retrofit;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.util.ReflectionTestUtils;
@@ -44,9 +41,6 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class InfluxDbAutoConfigurationTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(InfluxDbAutoConfiguration.class));

View File

@@ -36,8 +36,8 @@ import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfigurationServ
import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -54,7 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@DirtiesContext
@ExtendWith(OutputExtension.class)
@ExtendWith(OutputCaptureExtension.class)
public class JerseyAutoConfigurationServletContainerTests {
@Test

View File

@@ -43,8 +43,8 @@ import org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationList
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.testsupport.Assume;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -64,7 +64,7 @@ import static org.assertj.core.api.Assertions.contentOf;
* @author Stephane Nicoll
* @author Dominic Gunn
*/
@ExtendWith(OutputExtension.class)
@ExtendWith(OutputCaptureExtension.class)
public class LiquibaseAutoConfigurationTests {
@BeforeEach

View File

@@ -22,7 +22,7 @@ import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.impl.StaticLoggerBinder;
import org.springframework.boot.SpringApplication;
@@ -32,8 +32,8 @@ import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConf
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -53,26 +53,24 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Andy Wilkinson
* @author Madhura Bhave
*/
@ExtendWith(OutputCaptureExtension.class)
public class ConditionEvaluationReportLoggingListenerTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
private ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener();
@Test
public void logsDebugOnContextRefresh() {
public void logsDebugOnContextRefresh(CapturedOutput capturedOutput) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context);
context.register(Config.class);
context.refresh();
withDebugLogging(() -> this.initializer
.onApplicationEvent(new ContextRefreshedEvent(context)));
assertThat(this.output).contains("CONDITIONS EVALUATION REPORT");
assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT");
}
@Test
public void logsDebugOnError() {
public void logsDebugOnError(CapturedOutput capturedOutput) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context);
context.register(ErrorConfig.class);
@@ -80,11 +78,11 @@ public class ConditionEvaluationReportLoggingListenerTests {
(ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent(
new ApplicationFailedEvent(new SpringApplication(), new String[0],
context, ex))));
assertThat(this.output).contains("CONDITIONS EVALUATION REPORT");
assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT");
}
@Test
public void logsInfoOnErrorIfDebugDisabled() {
public void logsInfoOnErrorIfDebugDisabled(CapturedOutput capturedOutput) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context);
context.register(ErrorConfig.class);
@@ -92,13 +90,13 @@ public class ConditionEvaluationReportLoggingListenerTests {
.satisfies((ex) -> this.initializer.onApplicationEvent(
new ApplicationFailedEvent(new SpringApplication(), new String[0],
context, ex)));
assertThat(this.output).contains("Error starting"
assertThat(capturedOutput).contains("Error starting"
+ " ApplicationContext. To display the conditions report re-run"
+ " your application with 'debug' enabled.");
}
@Test
public void logsOutput() {
public void logsOutput(CapturedOutput capturedOutput) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context);
context.register(Config.class);
@@ -107,7 +105,7 @@ public class ConditionEvaluationReportLoggingListenerTests {
context.refresh();
withDebugLogging(() -> this.initializer
.onApplicationEvent(new ContextRefreshedEvent(context)));
assertThat(this.output)
assertThat(capturedOutput)
.contains("not a servlet web application (OnWebApplicationCondition)");
}
@@ -131,7 +129,7 @@ public class ConditionEvaluationReportLoggingListenerTests {
}
@Test
public void listenerWithInfoLevelShouldLogAtInfo() {
public void listenerWithInfoLevelShouldLogAtInfo(CapturedOutput capturedOutput) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
ConditionEvaluationReportLoggingListener initializer = new ConditionEvaluationReportLoggingListener(
LogLevel.INFO);
@@ -139,7 +137,7 @@ public class ConditionEvaluationReportLoggingListenerTests {
context.register(Config.class);
context.refresh();
initializer.onApplicationEvent(new ContextRefreshedEvent(context));
assertThat(this.output).contains("CONDITIONS EVALUATION REPORT");
assertThat(capturedOutput).contains("CONDITIONS EVALUATION REPORT");
}
@Test
@@ -150,11 +148,11 @@ public class ConditionEvaluationReportLoggingListenerTests {
}
@Test
public void noErrorIfNotInitialized() {
public void noErrorIfNotInitialized(CapturedOutput capturedOutput) {
this.initializer
.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(),
new String[0], null, new RuntimeException("Planned")));
assertThat(this.output).contains("Unable to provide the conditions report");
assertThat(capturedOutput).contains("Unable to provide the conditions report");
}
private void withDebugLogging(Runnable runnable) {

View File

@@ -21,7 +21,7 @@ import java.util.concurrent.Executor;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.quartz.Calendar;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
@@ -45,8 +45,8 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerA
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@@ -68,11 +68,9 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Vedran Pavic
* @author Stephane Nicoll
*/
@ExtendWith(OutputCaptureExtension.class)
public class QuartzAutoConfigurationTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.datasource.generate-unique-name=true")
.withConfiguration(AutoConfigurations.of(QuartzAutoConfiguration.class));
@@ -176,7 +174,7 @@ public class QuartzAutoConfigurationTests {
}
@Test
public void withConfiguredJobAndTrigger() {
public void withConfiguredJobAndTrigger(CapturedOutput capturedOutput) {
this.contextRunner.withUserConfiguration(QuartzFullConfiguration.class)
.withPropertyValues("test-name=withConfiguredJobAndTrigger")
.run((context) -> {
@@ -187,8 +185,8 @@ public class QuartzAutoConfigurationTests {
assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger")))
.isNotNull();
Thread.sleep(1000L);
assertThat(this.output).contains("withConfiguredJobAndTrigger");
assertThat(this.output).contains("jobDataValue");
assertThat(capturedOutput).contains("withConfiguredJobAndTrigger")
.contains("jobDataValue");
});
}

View File

@@ -21,7 +21,6 @@ import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage;
@@ -30,8 +29,6 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.test.City;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -65,9 +62,6 @@ public class SecurityAutoConfigurationTests {
.withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void testWebConfiguration() {
this.contextRunner.run((context) -> {

View File

@@ -21,7 +21,7 @@ import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -30,8 +30,8 @@ import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConf
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
@@ -51,19 +51,18 @@ import org.springframework.web.bind.annotation.RestController;
*
* @author Phillip Webb
*/
@ExtendWith(OutputCaptureExtension.class)
public class SecurityFilterAutoConfigurationEarlyInitializationTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void testSecurityFilterDoesNotCauseEarlyInitialization() {
public void testSecurityFilterDoesNotCauseEarlyInitialization(
CapturedOutput capturedOutput) {
try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext()) {
TestPropertyValues.of("server.port:0").applyTo(context);
context.register(Config.class);
context.refresh();
int port = context.getWebServer().getPort();
String password = this.output.toString()
String password = capturedOutput.toString()
.split("Using generated security password: ")[1].split("\n")[0]
.trim();
new TestRestTemplate("user", password)

View File

@@ -19,14 +19,14 @@ package org.springframework.boot.autoconfigure.security.servlet;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@@ -52,27 +52,26 @@ import static org.mockito.Mockito.mock;
*
* @author Madhura Bhave
*/
@ExtendWith(OutputCaptureExtension.class)
public class UserDetailsServiceAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withUserConfiguration(TestSecurityConfiguration.class).withConfiguration(
AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void testDefaultUsernamePassword() {
public void testDefaultUsernamePassword(CapturedOutput capturedOutput) {
this.contextRunner.run((context) -> {
UserDetailsService manager = context.getBean(UserDetailsService.class);
assertThat(this.output.toString())
assertThat(capturedOutput.toString())
.contains("Using generated security password:");
assertThat(manager.loadUserByUsername("user")).isNotNull();
});
}
@Test
public void defaultUserNotCreatedIfAuthenticationManagerBeanPresent() {
public void defaultUserNotCreatedIfAuthenticationManagerBeanPresent(
CapturedOutput capturedOutput) {
this.contextRunner
.withUserConfiguration(TestAuthenticationManagerConfiguration.class)
.run((context) -> {
@@ -80,7 +79,7 @@ public class UserDetailsServiceAutoConfigurationTests {
.getBean(AuthenticationManager.class);
assertThat(manager).isEqualTo(context.getBean(
TestAuthenticationManagerConfiguration.class).authenticationManager);
assertThat(this.output.toString())
assertThat(capturedOutput.toString())
.doesNotContain("Using generated security password: ");
TestingAuthenticationToken token = new TestingAuthenticationToken(
"foo", "bar");
@@ -89,26 +88,28 @@ public class UserDetailsServiceAutoConfigurationTests {
}
@Test
public void defaultUserNotCreatedIfUserDetailsServiceBeanPresent() {
public void defaultUserNotCreatedIfUserDetailsServiceBeanPresent(
CapturedOutput capturedOutput) {
this.contextRunner
.withUserConfiguration(TestUserDetailsServiceConfiguration.class)
.run((context) -> {
UserDetailsService userDetailsService = context
.getBean(UserDetailsService.class);
assertThat(this.output.toString())
assertThat(capturedOutput.toString())
.doesNotContain("Using generated security password: ");
assertThat(userDetailsService.loadUserByUsername("foo")).isNotNull();
});
}
@Test
public void defaultUserNotCreatedIfAuthenticationProviderBeanPresent() {
public void defaultUserNotCreatedIfAuthenticationProviderBeanPresent(
CapturedOutput capturedOutput) {
this.contextRunner
.withUserConfiguration(TestAuthenticationProviderConfiguration.class)
.run((context) -> {
AuthenticationProvider provider = context
.getBean(AuthenticationProvider.class);
assertThat(this.output.toString())
assertThat(capturedOutput.toString())
.doesNotContain("Using generated security password: ");
TestingAuthenticationToken token = new TestingAuthenticationToken(
"foo", "bar");
@@ -153,10 +154,11 @@ public class UserDetailsServiceAutoConfigurationTests {
}
@Test
public void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed() {
public void generatedPasswordShouldNotBePrintedIfAuthenticationManagerBuilderIsUsed(
CapturedOutput capturedOutput) {
this.contextRunner
.withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class)
.run(((context) -> assertThat(this.output.toString())
.run(((context) -> assertThat(capturedOutput.toString())
.doesNotContain("Using generated security password: ")));
}

View File

@@ -21,7 +21,7 @@ import java.util.concurrent.Future;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.task.TaskExecutorBuilder;
@@ -29,8 +29,8 @@ import org.springframework.boot.task.TaskExecutorCustomizer;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SyncTaskExecutor;
@@ -53,15 +53,13 @@ import static org.mockito.Mockito.verify;
* @author Stephane Nicoll
* @author Camille Vienot
*/
@ExtendWith(OutputCaptureExtension.class)
public class TaskExecutionAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(TaskExecutionAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void taskExecutorBuilderShouldApplyCustomSettings() {
this.contextRunner
@@ -113,15 +111,14 @@ public class TaskExecutionAutoConfigurationTests {
}
@Test
public void taskExecutorAutoConfigured() {
public void taskExecutorAutoConfigured(CapturedOutput capturedOutput) {
this.contextRunner.run((context) -> {
assertThat(this.output.toString())
.doesNotContain("Initializing ExecutorService");
assertThat(capturedOutput).doesNotContain("Initializing ExecutorService");
assertThat(context).hasSingleBean(Executor.class);
assertThat(context).hasBean("applicationTaskExecutor");
assertThat(context).getBean("applicationTaskExecutor")
.isInstanceOf(ThreadPoolTaskExecutor.class);
assertThat(this.output.toString()).contains("Initializing ExecutorService");
assertThat(capturedOutput).contains("Initializing ExecutorService");
});
}

View File

@@ -23,7 +23,7 @@ import java.util.Locale;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingRespectLayoutTitleStrategy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;
@@ -37,8 +37,8 @@ import org.thymeleaf.templateresolver.ITemplateResolver;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.testsupport.BuildOutput;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -58,11 +58,9 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Kazuki Shimizu
* @author Stephane Nicoll
*/
@ExtendWith(OutputCaptureExtension.class)
public class ThymeleafReactiveAutoConfigurationTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
private final BuildOutput buildOutput = new BuildOutput(getClass());
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
@@ -187,21 +185,21 @@ public class ThymeleafReactiveAutoConfigurationTests {
}
@Test
public void templateLocationDoesNotExist() {
public void templateLocationDoesNotExist(CapturedOutput capturedOutput) {
this.contextRunner
.withPropertyValues(
"spring.thymeleaf.prefix:classpath:/no-such-directory/")
.run((context) -> assertThat(this.output)
.run((context) -> assertThat(capturedOutput)
.contains("Cannot find template location"));
}
@Test
public void templateLocationEmpty() {
public void templateLocationEmpty(CapturedOutput capturedOutput) {
new File(this.buildOutput.getTestResourcesLocation(),
"empty-templates/empty-directory").mkdirs();
this.contextRunner.withPropertyValues(
"spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/")
.run((context) -> assertThat(this.output.toString())
.run((context) -> assertThat(capturedOutput)
.doesNotContain("Cannot find template location"));
}

View File

@@ -41,7 +41,7 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.testsupport.BuildOutput;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter;
@@ -75,7 +75,7 @@ import static org.hamcrest.Matchers.not;
public class ThymeleafServletAutoConfigurationTests {
@Rule
public OutputCapture output = new OutputCapture();
public OutputCaptureRule output = new OutputCaptureRule();
private final BuildOutput buildOutput = new BuildOutput(getClass());

View File

@@ -21,7 +21,7 @@ import java.nio.charset.StandardCharsets;
import javax.validation.Valid;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.core.publisher.Mono;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@@ -32,8 +32,8 @@ import org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFact
import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
import org.springframework.boot.test.context.assertj.AssertableReactiveWebApplicationContext;
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -56,6 +56,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
*
* @author Brian Clozel
*/
@ExtendWith(OutputCaptureExtension.class)
public class DefaultErrorWebExceptionHandlerIntegrationTests {
private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html",
@@ -63,9 +64,6 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
private final LogIdFilter logIdFilter = new LogIdFilter();
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
ReactiveWebServerFactoryAutoConfiguration.class,
@@ -78,7 +76,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
.withUserConfiguration(Application.class);
@Test
public void jsonError() {
public void jsonError(CapturedOutput capturedOutput) {
this.contextRunner.run((context) -> {
WebTestClient client = getWebClient(context);
client.get().uri("/").exchange().expectStatus()
@@ -89,7 +87,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
.isEqualTo("Expected!").jsonPath("exception").doesNotExist()
.jsonPath("trace").doesNotExist().jsonPath("requestId")
.isEqualTo(this.logIdFilter.getLogId());
assertThat(this.output).contains("500 Server Error for HTTP GET \"/\"")
assertThat(capturedOutput).contains("500 Server Error for HTTP GET \"/\"")
.contains("java.lang.IllegalStateException: Expected!");
});
}

View File

@@ -17,13 +17,13 @@
package org.springframework.boot.autoconfigure.web.servlet.error;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.test.extension.CapturedOutput;
import org.springframework.boot.test.extension.OutputExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -38,6 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Brian Clozel
*/
@ExtendWith(OutputCaptureExtension.class)
public class ErrorMvcAutoConfigurationTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
@@ -45,9 +46,6 @@ public class ErrorMvcAutoConfigurationTests {
AutoConfigurations.of(DispatcherServletAutoConfiguration.class,
ErrorMvcAutoConfiguration.class));
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Test
public void renderContainsViewWithExceptionDetails() throws Exception {
this.contextRunner.run((context) -> {
@@ -69,7 +67,7 @@ public class ErrorMvcAutoConfigurationTests {
}
@Test
public void renderWhenAlreadyCommittedLogsMessage() {
public void renderWhenAlreadyCommittedLogsMessage(CapturedOutput capturedOutput) {
this.contextRunner.run((context) -> {
View errorView = context.getBean("error", View.class);
ErrorAttributes errorAttributes = context.getBean(ErrorAttributes.class);
@@ -77,7 +75,7 @@ public class ErrorMvcAutoConfigurationTests {
new IllegalStateException("Exception message"), true);
errorView.render(errorAttributes.getErrorAttributes(webRequest, true),
webRequest.getRequest(), webRequest.getResponse());
assertThat(this.output)
assertThat(capturedOutput)
.contains("Cannot render error page for request [/path] "
+ "and exception [Exception message] as the response has "
+ "already been committed. As a result, the response may "

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,7 +42,7 @@ import org.springframework.boot.cli.command.OptionParsingCommand;
import org.springframework.boot.cli.command.archive.JarCommand;
import org.springframework.boot.cli.command.grab.GrabCommand;
import org.springframework.boot.cli.command.run.RunCommand;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.testsupport.BuildOutput;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
@@ -60,7 +60,9 @@ public class CliTester implements TestRule {
private final BuildOutput buildOutput = new BuildOutput(getClass());
private final OutputCapture outputCapture = new OutputCapture();
private final OutputCaptureRule outputCapture = new OutputCaptureRule();
private String previousOutput = "";
private long timeout = TimeUnit.MINUTES.toMillis(6);
@@ -170,8 +172,9 @@ public class CliTester implements TestRule {
}
private String getOutput() {
String output = this.outputCapture.toString();
this.outputCapture.reset();
String output = this.outputCapture.toString()
.substring(this.previousOutput.length());
this.previousOutput = output;
return output;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.cli.command.run.RunCommand;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import static org.assertj.core.api.Assertions.assertThat;
@@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class CommandRunnerIntegrationTests {
@Rule
public OutputCapture output = new OutputCapture();
public OutputCaptureRule output = new OutputCaptureRule();
@Test
public void debugAddsAutoconfigReport() {

View File

@@ -37,7 +37,7 @@ import org.springframework.boot.devtools.remote.server.Dispatcher;
import org.springframework.boot.devtools.remote.server.DispatcherFilter;
import org.springframework.boot.devtools.restart.MockRestarter;
import org.springframework.boot.devtools.restart.RestartScopeInitializer;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
@@ -65,7 +65,7 @@ public class RemoteClientConfigurationTests {
public MockRestarter restarter = new MockRestarter();
@Rule
public OutputCapture output = new OutputCapture();
public OutputCaptureRule output = new OutputCaptureRule();
private AnnotationConfigServletWebServerApplicationContext context;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +28,7 @@ import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.test.util.ReflectionTestUtils;
@@ -50,7 +50,7 @@ public class RestartApplicationListenerTests {
private static final String[] ARGS = new String[] { "a", "b", "c" };
@Rule
public final OutputCapture output = new OutputCapture();
public final OutputCaptureRule output = new OutputCaptureRule();
@Before
@After
@@ -86,7 +86,6 @@ public class RestartApplicationListenerTests {
@Test
public void disableWithSystemProperty() {
System.setProperty(ENABLED_PROPERTY, "false");
this.output.reset();
testInitialize(false);
assertThat(Restarter.getInstance()).hasFieldOrPropertyWithValue("enabled", false);
assertThat(this.output.toString())

View File

@@ -31,7 +31,7 @@ import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
@@ -57,7 +57,7 @@ import static org.mockito.Mockito.verifyZeroInteractions;
public class RestarterTests {
@Rule
public OutputCapture out = new OutputCapture();
public OutputCaptureRule out = new OutputCaptureRule();
@Before
public void setup() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ import org.mockito.MockitoAnnotations;
import org.springframework.boot.devtools.test.MockClientHttpRequestFactory;
import org.springframework.boot.devtools.tunnel.client.HttpTunnelConnection.TunnelChannel;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.http.HttpStatus;
import static org.assertj.core.api.Assertions.assertThat;
@@ -53,7 +53,7 @@ import static org.mockito.Mockito.verify;
public class HttpTunnelConnectionTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
public OutputCaptureRule outputCapture = new OutputCaptureRule();
private String url;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
@@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class SpringApplicationBuilderExampleTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
public OutputCaptureRule outputCapture = new OutputCaptureRule();
@Test
public void contextHierarchyWithDisabledBanner() {

View File

@@ -21,7 +21,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
@@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PropertiesMigrationListenerTests {
@Rule
public final OutputCapture output = new OutputCapture();
public final OutputCaptureRule output = new OutputCaptureRule();
private ConfigurableApplicationContext context;

View File

@@ -23,7 +23,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
@@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock;
public class SpringBootDependencyInjectionTestExecutionListenerTests {
@Rule
public OutputCapture out = new OutputCapture();
public OutputCaptureRule out = new OutputCaptureRule();
private SpringBootDependencyInjectionTestExecutionListener reportListener = new SpringBootDependencyInjectionTestExecutionListener();

View File

@@ -25,7 +25,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMock
import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.context.ApplicationContext;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
@@ -49,7 +49,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class MockMvcSpringBootTestIntegrationTests {
@Rule
public OutputCapture output = new OutputCapture();
public OutputCaptureRule output = new OutputCaptureRule();
@MockBean
private ExampleMockableService service;

View File

@@ -23,7 +23,7 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@@ -45,7 +45,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class WebMvcTestPrintAlwaysIntegrationTests {
@Rule
public OutputCapture output = new OutputCapture();
public OutputCaptureRule output = new OutputCaptureRule();
@Autowired
private MockMvc mvc;

View File

@@ -22,7 +22,7 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@@ -45,7 +45,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class WebMvcTestPrintDefaultOverrideIntegrationTests {
@Rule
public OutputCapture output = new OutputCapture();
public OutputCaptureRule output = new OutputCaptureRule();
@Autowired
private MockMvc mvc;

View File

@@ -20,7 +20,7 @@ import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.Matchers.containsString;
@@ -41,7 +41,7 @@ public class WebMvcTestPrintDefaultRunner extends SpringJUnit4ClassRunner {
protected Statement methodBlock(FrameworkMethod frameworkMethod) {
Statement statement = super.methodBlock(frameworkMethod);
statement = new AlwaysPassStatement(statement);
OutputCapture outputCapture = new OutputCapture();
OutputCaptureRule outputCapture = new OutputCaptureRule();
if (frameworkMethod.getName().equals("shouldPrint")) {
outputCapture.expect(containsString("HTTP Method"));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,23 +16,12 @@
package org.springframework.boot.test.rule;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matcher;
import org.junit.Assert;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiOutput.Enabled;
import static org.hamcrest.Matchers.allOf;
import org.springframework.boot.test.system.OutputCaptureRule;
/**
* JUnit {@code @Rule} to capture output from System.out and System.err.
@@ -40,78 +29,32 @@ import static org.hamcrest.Matchers.allOf;
* @author Phillip Webb
* @author Andy Wilkinson
* @since 1.4.0
* @deprecated since 2.2.0 in favor of {@link OutputCaptureRule}
*/
@Deprecated
public class OutputCapture implements TestRule {
private CaptureOutputStream captureOut;
private CaptureOutputStream captureErr;
private ByteArrayOutputStream copy;
private List<Matcher<? super String>> matchers = new ArrayList<>();
private final OutputCaptureRule delegate = new OutputCaptureRule();
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
captureOutput();
try {
base.evaluate();
}
finally {
try {
if (!OutputCapture.this.matchers.isEmpty()) {
String output = OutputCapture.this.toString();
Assert.assertThat(output, allOf(OutputCapture.this.matchers));
}
}
finally {
releaseOutput();
}
}
}
};
}
protected void captureOutput() {
AnsiOutputControl.get().disableAnsiOutput();
this.copy = new ByteArrayOutputStream();
this.captureOut = new CaptureOutputStream(System.out, this.copy);
this.captureErr = new CaptureOutputStream(System.err, this.copy);
System.setOut(new PrintStream(this.captureOut));
System.setErr(new PrintStream(this.captureErr));
}
protected void releaseOutput() {
AnsiOutputControl.get().enabledAnsiOutput();
System.setOut(this.captureOut.getOriginal());
System.setErr(this.captureErr.getOriginal());
this.copy = null;
return this.delegate.apply(base, description);
}
/**
* Discard all currently accumulated output.
*/
public void reset() {
this.copy.reset();
this.delegate.reset();
}
public void flush() {
try {
this.captureOut.flush();
this.captureErr.flush();
}
catch (IOException ex) {
// ignore
}
// Flushing is no longer necessary
}
@Override
public String toString() {
flush();
return this.copy.toString();
return this.delegate.toString();
}
/**
@@ -120,85 +63,7 @@ public class OutputCapture implements TestRule {
* @param matcher the matcher
*/
public void expect(Matcher<? super String> matcher) {
this.matchers.add(matcher);
}
private static class CaptureOutputStream extends OutputStream {
private final PrintStream original;
private final OutputStream copy;
CaptureOutputStream(PrintStream original, OutputStream copy) {
this.original = original;
this.copy = copy;
}
@Override
public void write(int b) throws IOException {
this.copy.write(b);
this.original.write(b);
this.original.flush();
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.copy.write(b, off, len);
this.original.write(b, off, len);
}
public PrintStream getOriginal() {
return this.original;
}
@Override
public void flush() throws IOException {
this.copy.flush();
this.original.flush();
}
}
/**
* Allow AnsiOutput to not be on the test classpath.
*/
private static class AnsiOutputControl {
public void disableAnsiOutput() {
}
public void enabledAnsiOutput() {
}
public static AnsiOutputControl get() {
try {
Class.forName("org.springframework.boot.ansi.AnsiOutput");
return new AnsiPresentOutputControl();
}
catch (ClassNotFoundException ex) {
return new AnsiOutputControl();
}
}
}
private static class AnsiPresentOutputControl extends AnsiOutputControl {
@Override
public void disableAnsiOutput() {
AnsiOutput.setEnabled(Enabled.NEVER);
}
@Override
public void enabledAnsiOutput() {
AnsiOutput.setEnabled(Enabled.DETECT);
}
this.delegate.expect(matcher);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.system;
/**
* Provides access to {@link System#out System.out} and {@link System#err System.err}
* output that has been capture by the {@link OutputCaptureExtension}. Can be used to
* apply assertions either using AssertJ or standard JUnit assertions. For example:
* <pre class="code">
* assertThat(output).contains("started"); // Checks all output
* assertThat(output.getErr()).contains("failed"); // Only checks System.err
* assertThat(output.getOut()).contains("ok"); // Only checks System.put
* </pre>
*
* @author Madhura Bhave
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.2.0
* @see OutputCaptureExtension
*/
public interface CapturedOutput extends CharSequence {
@Override
default int length() {
return toString().length();
}
@Override
default char charAt(int index) {
return toString().charAt(index);
}
@Override
default CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
/**
* Return all content (both {@link System#out System.out} and {@link System#err
* System.err}) in the order that it was was captured.
* @return all captured output
*/
String getAll();
/**
* Return {@link System#out System.out} content in the order that it was was captured.
* @return {@link System#out System.out} captured output
*/
String getOut();
/**
* Return {@link System#err System.err} content in the order that it was was captured.
* @return {@link System#err System.err} captured output
*/
String getErr();
}

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.boot.test.extension;
package org.springframework.boot.test.system;
import java.io.IOException;
import java.io.OutputStream;
@@ -27,41 +27,32 @@ import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.junit.jupiter.api.extension.Extension;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiOutput.Enabled;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Provides access to {@link System#out System.out} and {@link System#err System.err}
* output that has been capture by the {@link OutputExtension}. Can be used to apply
* assertions either using AssertJ or standard JUnit assertions. For example:
* <pre class="code">
* assertThat(output).contains("started"); // Checks all output
* assertThat(output.getErr()).contains("failed"); // Only checks System.err
* assertThat(output.getOut()).contains("ok"); // Only checks System.put
* </pre>
* Provides support for capturing {@link System#out System.out} and {@link System#err
* System.err}.
*
* @author Madhura Bhave
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.2.0
* @see OutputExtension
* @see OutputCaptureExtension
* @see OutputCaptureRule
*/
public class CapturedOutput implements CharSequence, Extension {
class OutputCapture implements CapturedOutput {
private final Deque<SystemCapture> systemCaptures = new ArrayDeque<>();
private AnsiOutputState ansiOutputState;
protected CapturedOutput() {
}
/**
* Push a new system capture session onto the stack.
*/
protected final void push() {
final void push() {
if (this.systemCaptures.isEmpty()) {
this.ansiOutputState = AnsiOutputState.saveAndDisable();
}
@@ -71,7 +62,7 @@ public class CapturedOutput implements CharSequence, Extension {
/**
* Pop the last system capture session from the stack.
*/
protected final void pop() {
final void pop() {
this.systemCaptures.removeLast().release();
if (this.systemCaptures.isEmpty() && this.ansiOutputState != null) {
this.ansiOutputState.restore();
@@ -79,21 +70,6 @@ public class CapturedOutput implements CharSequence, Extension {
}
}
@Override
public int length() {
return toString().length();
}
@Override
public char charAt(int index) {
return toString().charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
@@ -120,6 +96,7 @@ public class CapturedOutput implements CharSequence, Extension {
* System.err}) in the order that it was was captured.
* @return all captured output
*/
@Override
public String getAll() {
return get((type) -> true);
}
@@ -128,6 +105,7 @@ public class CapturedOutput implements CharSequence, Extension {
* Return {@link System#out System.out} content in the order that it was was captured.
* @return {@link System#out System.out} captured output
*/
@Override
public String getOut() {
return get(Type.OUT::equals);
}
@@ -136,10 +114,18 @@ public class CapturedOutput implements CharSequence, Extension {
* Return {@link System#err System.err} content in the order that it was was captured.
* @return {@link System#err System.err} captured output
*/
@Override
public String getErr() {
return get(Type.ERR::equals);
}
/**
* Resets the current capture session, clearing its captured output.
*/
void reset() {
this.systemCaptures.peek().reset();
}
private String get(Predicate<Type> filter) {
Assert.state(!this.systemCaptures.isEmpty(),
"No system captures found. Check that you have used @RegisterExtension "
@@ -192,6 +178,10 @@ public class CapturedOutput implements CharSequence, Extension {
}
}
public void reset() {
this.capturedStrings.clear();
}
}
/**
@@ -303,7 +293,7 @@ public class CapturedOutput implements CharSequence, Extension {
public static AnsiOutputState saveAndDisable() {
if (!ClassUtils.isPresent("org.springframework.boot.ansi.AnsiOutput",
CapturedOutput.class.getClassLoader())) {
OutputCapture.class.getClassLoader())) {
return null;
}
return new AnsiOutputState();

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.boot.test.extension;
package org.springframework.boot.test.system;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
@@ -25,74 +25,62 @@ import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.RegisterExtension;
/**
* JUnit5 {@code @Extension} to capture output {@link System#out System.out} and
* JUnit 5 {@code @Extension} to capture {@link System#out System.out} and
* {@link System#err System.err}. Can be used on a test class via
* {@link ExtendWith @ExtendWith}, or on field using
* {@link RegisterExtension @RegisterExtension}. This extension provides access to
* {@link CapturedOutput} instances which can be used to assert that the correct output
* was written.
* {@link ExtendWith @ExtendWith}. This extension provides {@link ParameterResolver
* parameter resolution} for a {@link CapturedOutput} instance which can be used to assert
* that the correct output was written.
* <p>
* To use with {@link ExtendWith @ExtendWith}, inject the {@link CapturedOutput} as a test
* argument: <pre class="code">
* To use with {@link ExtendWith @ExtendWith}, inject the {@link CapturedOutput} as an
* argument to your test class constructor or test method:
*
* <pre class="code">
* &#064;ExtendWith(OutputExtension.class)
* class MyTest {
*
* &#064;Test
* void test(CapturedOutput output) {
* assertThat(output).contains("ok");
* }
*
* }
* </pre>
* <p>
* To use with {@link RegisterExtension @RegisterExtension}, use the {@link #capture()
* capture} factory method: argument: <pre class="code">
* class MyTest {
*
* &#064;RegisterExtension
* CapturedOutput output = OutputExtension.capture();
*
* &#064;Test
* void test() {
* assertThat(output).contains("ok");
* }
* &#064;Test
* void test(CapturedOutput output) {
* assertThat(output).contains("ok");
* }
*
* }
* </pre>
*
* @author Madhura Bhave
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.2.0
* @see CapturedOutput
*/
public class OutputExtension extends CapturedOutput implements BeforeAllCallback,
AfterAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver {
public class OutputCaptureExtension implements BeforeAllCallback, AfterAllCallback,
BeforeEachCallback, AfterEachCallback, ParameterResolver {
OutputExtension() {
private final OutputCapture outputCapture = new OutputCapture();
OutputCaptureExtension() {
// Package private to prevent users from directly creating an instance.
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
push();
this.outputCapture.push();
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
pop();
this.outputCapture.pop();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
push();
this.outputCapture.push();
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
pop();
this.outputCapture.pop();
}
@Override
@@ -104,15 +92,7 @@ public class OutputExtension extends CapturedOutput implements BeforeAllCallback
@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
return this;
}
/**
* Factory method for use with {@link RegisterExtension @RegisterExtension} fields.
* @return a new {@link CapturedOutput} instance
*/
public static CapturedOutput capture() {
return new OutputExtension();
return this.outputCapture;
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.system;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matcher;
import org.junit.Assert;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import static org.hamcrest.Matchers.allOf;
/**
* JUnit {@code @Rule} to capture output from System.out and System.err.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.2.0
*/
public class OutputCaptureRule implements TestRule {
private final org.springframework.boot.test.system.OutputCapture delegate = new org.springframework.boot.test.system.OutputCapture();
private List<Matcher<? super String>> matchers = new ArrayList<>();
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
OutputCaptureRule.this.delegate.push();
try {
base.evaluate();
}
finally {
try {
if (!OutputCaptureRule.this.matchers.isEmpty()) {
String output = OutputCaptureRule.this.delegate.toString();
Assert.assertThat(output,
allOf(OutputCaptureRule.this.matchers));
}
}
finally {
OutputCaptureRule.this.delegate.pop();
}
}
}
};
}
/**
* Resets the current capture session, clearing its captured output.
* @deprecated since 2.2 with no replacement
*/
@Deprecated
public void reset() {
OutputCaptureRule.this.delegate.reset();
}
@Override
public String toString() {
return this.delegate.toString();
}
/**
* Verify that the output is matched by the supplied {@code matcher}. Verification is
* performed after the test method has executed.
* @param matcher the matcher
*/
public void expect(Matcher<? super String> matcher) {
this.matchers.add(matcher);
}
}

View File

@@ -15,6 +15,6 @@
*/
/**
* JUnit 5 {@link org.junit.jupiter.api.extension.Extension Extensions}.
* Classes for {@link java.lang.System System}-related testing.
*/
package org.springframework.boot.test.extension;
package org.springframework.boot.test.system;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.boot.testsupport.runner.classpath.ClassPathOverrides;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
@@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DuplicateJsonObjectContextCustomizerFactoryTests {
@Rule
public OutputCapture output = new OutputCapture();
public OutputCaptureRule output = new OutputCaptureRule();
@Test
public void warningForMultipleVersions() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Roland Weisleder
*/
@Deprecated
public class OutputCaptureTests {
@Rule

View File

@@ -13,29 +13,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.extension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
package org.springframework.boot.test.system;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OutputExtension} when used via
* {@link RegisterExtension @RegisterExtension}.
* Tests for {@link OutputCaptureRule}.
*
* @author Madhura Bhave
* @author Roland Weisleder
*/
class OutputExtensionRegisterExtensionTests {
public class OutputCaptureRuleTests {
@RegisterExtension
CapturedOutput output = OutputExtension.capture();
@Rule
public OutputCaptureRule outputCapture = new OutputCaptureRule();
@Test
void captureShouldReturnAllCapturedOutput() {
public void toStringShouldReturnAllCapturedOutput() {
System.out.println("Hello World");
System.err.println("Error!!!");
assertThat(this.output).contains("Hello World").contains("Error!!!");
assertThat(this.outputCapture.toString()).contains("Hello World");
}
}

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.boot.test.extension;
package org.springframework.boot.test.system;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
@@ -28,11 +28,11 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link CapturedOutput}.
* Tests for {@link OutputCapture}.
*
* @author Phillip Webb
*/
class CapturedOutputTests {
class OutputCaptureTests {
private PrintStream originalOut;
@@ -42,7 +42,7 @@ class CapturedOutputTests {
private TestPrintStream systemErr;
private CapturedOutput output = new CapturedOutput();
private OutputCapture output = new OutputCapture();
@BeforeEach
void replaceSystemStreams() {

View File

@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.extension;
package org.springframework.boot.test.system;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.BeforeAllCallback;
@@ -23,11 +23,11 @@ import org.junit.jupiter.api.extension.ExtensionContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OutputExtension} when used via {@link ExtendWith @ExtendWith}.
* Tests for {@link OutputCaptureExtension} when used via {@link ExtendWith @ExtendWith}.
*
* @author Madhura Bhave
*/
@ExtendWith(OutputExtension.class)
@ExtendWith(OutputCaptureExtension.class)
@ExtendWith(OutputExtensionExtendWithTests.BeforeAllExtension.class)
class OutputExtensionExtendWithTests {