From 503d10a3742060ea684eb28dec1502143cc606c2 Mon Sep 17 00:00:00 2001 From: dreis2211 Date: Thu, 11 Jul 2019 17:55:44 +0200 Subject: [PATCH 1/2] Provide a JUnit 5 equivalent of ModifiedClassPathRunner --- ...4jLoggerContextAutoConfigurationTests.java | 14 +- ...onfigurationWithLog4j2AndLogbackTests.java | 12 +- ...HealthIndicatorAutoConfigurationTests.java | 14 +- ...ldManagementContextConfigurationTests.java | 22 +- ...meManagementContextConfigurationTests.java | 24 +- ...atchAutoConfigurationWithoutJdbcTests.java | 8 +- ...BatchAutoConfigurationWithoutJpaTests.java | 14 +- .../cache/CacheAutoConfigurationTests.java | 114 ++++---- .../EhCache2CacheAutoConfigurationTests.java | 18 +- .../EhCache3CacheAutoConfigurationTests.java | 14 +- ...MissingBeanWithFilteredClasspathTests.java | 27 +- ...eanConditionTypeDeductionFailureTests.java | 12 +- .../RedisAutoConfigurationJedisTests.java | 34 +-- ...aAutoConfigurationWithoutJacksonTests.java | 12 +- ...HazelcastAutoConfigurationServerTests.java | 30 +- ...sAutoConfigurationWithoutJacksonTests.java | 30 +- ...ourceBeanCreationFailureAnalyzerTests.java | 14 +- ...bAutoConfigurationWithNoProviderTests.java | 12 +- ...ibernate2ndLevelCacheIntegrationTests.java | 12 +- ...AutoConfigurationWithoutSecurityTests.java | 12 +- ...hHibernateValidatorMissingElImplTests.java | 33 +-- ...utoConfigurationWithoutValidatorTests.java | 33 +-- ...eddedDataSourceAutoConfigurationTests.java | 12 +- ...abaseAutoConfigurationNoEmbeddedTests.java | 14 +- ...ientTestWithComponentIntegrationTests.java | 12 +- ...entTestWithoutJacksonIntegrationTests.java | 32 ++- ...onObjectContextCustomizerFactoryTests.java | 28 +- .../spring-boot-test-support/pom.xml | 4 + .../runner/classpath/ClassPathExclusions.java | 4 +- .../runner/classpath/ClassPathOverrides.java | 4 +- .../ModifiedClassPathClassLoader.java | 46 +++ .../ModifiedClassPathClassLoaderFactory.java | 249 +++++++++++++++++ .../classpath/ModifiedClassPathExtension.java | 108 ++++++++ .../classpath/ModifiedClassPathRunner.java | 201 +------------- ...fiedClassPathExtensionExclusionsTests.java | 53 ++++ ...ifiedClassPathExtensionOverridesTests.java | 48 ++++ ...odifiedClassPathRunnerExclusionsTests.java | 1 + ...ModifiedClassPathRunnerOverridesTests.java | 1 + .../boot/SpringApplicationNoWebTests.java | 29 +- .../LoggingApplicationListenerTests.java | 262 +++++++++--------- .../NoSuchMethodFailureAnalyzerTests.java | 12 +- ...lidationExceptionFailureAnalyzerTests.java | 14 +- .../NoSnakeYamlPropertySourceLoaderTests.java | 12 +- .../DataSourceUnwrapperNoSpringJdbcTests.java | 14 +- ...latorFactoryWithoutElIntegrationTests.java | 14 +- ...eSenderBuilderOkHttp3IntegrationTests.java | 14 +- ...geSenderBuilderSimpleIntegrationTests.java | 14 +- src/checkstyle/checkstyle-suppressions.xml | 1 - src/checkstyle/checkstyle.xml | 4 +- 49 files changed, 1001 insertions(+), 721 deletions(-) create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoader.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoaderFactory.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionExclusionsTests.java create mode 100644 spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java index 62817da39797..f7947b58197f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java @@ -18,14 +18,14 @@ import io.micrometer.core.instrument.binder.logging.Log4j2Metrics; import org.apache.logging.log4j.LogManager; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathOverrides; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,22 +36,22 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathOverrides("org.apache.logging.log4j:log4j-core:2.11.1") -public class Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests { +class Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test - public void autoConfiguresLog4J2Metrics() { + void autoConfiguresLog4J2Metrics() { assertThat(LogManager.getContext().getClass().getName()) .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class)); } @Test - public void allowsCustomLog4J2MetricsToBeUsed() { + void allowsCustomLog4J2MetricsToBeUsed() { assertThat(LogManager.getContext().getClass().getName()) .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); this.contextRunner.withUserConfiguration(CustomLog4J2MetricsConfiguration.class).run( diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java index 844c294802ae..2e2c78c9ec1e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationWithLog4j2AndLogbackTests.java @@ -17,13 +17,13 @@ package org.springframework.boot.actuate.autoconfigure.metrics; import io.micrometer.core.instrument.binder.logging.LogbackMetrics; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +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.testsupport.runner.classpath.ClassPathOverrides; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -33,15 +33,15 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathOverrides({ "org.apache.logging.log4j:log4j-core:2.9.0", "org.apache.logging.log4j:log4j-slf4j-impl:2.9.0" }) -public class MetricsAutoConfigurationWithLog4j2AndLogbackTests { +class MetricsAutoConfigurationWithLog4j2AndLogbackTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)); @Test - public void doesNotConfigureLogbackMetrics() { + void doesNotConfigureLogbackMetrics() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LogbackMetrics.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java index 56694f741da9..9e997e4d837d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorAutoConfigurationTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.actuate.autoconfigure.redis; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorAutoConfiguration; import org.springframework.boot.actuate.health.ApplicationHealthIndicator; @@ -27,7 +27,7 @@ import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -36,22 +36,22 @@ * * @author Phillip Webb */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions({ "reactor-core*.jar", "lettuce-core*.jar" }) -public class RedisHealthIndicatorAutoConfigurationTests { +class RedisHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, RedisHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); @Test - public void runShouldCreateIndicator() { + void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RedisHealthIndicator.class) .doesNotHaveBean(RedisReactiveHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); } @Test - public void runWhenDisabledShouldNotCreateIndicator() { + void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(RedisHealthIndicator.class) .doesNotHaveBean(RedisReactiveHealthIndicator.class) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java index 582d3aee94b2..7dedc6c49431 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java @@ -18,8 +18,8 @@ import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.jersey.ResourceConfigCustomizer; @@ -28,7 +28,7 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -43,15 +43,15 @@ * @author Andy Wilkinson * @author Madhura Bhave */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("spring-webmvc-*") -public class JerseyChildManagementContextConfigurationTests { +class JerseyChildManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withUserConfiguration(JerseyChildManagementContextConfiguration.class); @Test - public void autoConfigurationIsConditionalOnServletWebApplication() { + void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner @@ -59,13 +59,13 @@ public void autoConfigurationIsConditionalOnServletWebApplication() { } @Test - public void autoConfigurationIsConditionalOnClassResourceConfig() { + void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test - public void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { + void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { this.contextRunner.withUserConfiguration(CustomizerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class); @@ -75,7 +75,7 @@ public void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { } @Test - public void jerseyApplicationPathIsAutoConfigured() { + void jerseyApplicationPathIsAutoConfigured() { this.contextRunner.run((context) -> { JerseyApplicationPath bean = context.getBean(JerseyApplicationPath.class); assertThat(bean.getPath()).isEqualTo("/"); @@ -84,7 +84,7 @@ public void jerseyApplicationPathIsAutoConfigured() { @Test @SuppressWarnings("unchecked") - public void servletRegistrationBeanIsAutoConfigured() { + void servletRegistrationBeanIsAutoConfigured() { this.contextRunner.run((context) -> { ServletRegistrationBean bean = context.getBean(ServletRegistrationBean.class); assertThat(bean.getUrlMappings()).containsExactly("/*"); @@ -92,7 +92,7 @@ public void servletRegistrationBeanIsAutoConfigured() { } @Test - public void resourceConfigCustomizerBeanIsNotRequired() { + void resourceConfigCustomizerBeanIsNotRequired() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ResourceConfig.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java index 22a33b5fcdc2..1e7bb2894018 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java @@ -17,8 +17,8 @@ import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.jersey.ResourceConfigCustomizer; @@ -28,7 +28,7 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -42,15 +42,15 @@ * * @author Madhura Bhave */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("spring-webmvc-*") -public class JerseySameManagementContextConfigurationTests { +class JerseySameManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); @Test - public void autoConfigurationIsConditionalOnServletWebApplication() { + void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner @@ -58,13 +58,13 @@ public void autoConfigurationIsConditionalOnServletWebApplication() { } @Test - public void autoConfigurationIsConditionalOnClassResourceConfig() { + void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test - public void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { + void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { this.contextRunner.withUserConfiguration(CustomizerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class); @@ -74,12 +74,12 @@ public void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { } @Test - public void jerseyApplicationPathIsAutoConfiguredWhenNeeded() { + void jerseyApplicationPathIsAutoConfiguredWhenNeeded() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultJerseyApplicationPath.class)); } @Test - public void jerseyApplicationPathIsConditionalOnMissingBean() { + void jerseyApplicationPathIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ConfigWithJerseyApplicationPath.class).run((context) -> { assertThat(context).hasSingleBean(JerseyApplicationPath.class); assertThat(context).hasBean("testJerseyApplicationPath"); @@ -87,7 +87,7 @@ public void jerseyApplicationPathIsConditionalOnMissingBean() { } @Test - public void existingResourceConfigBeanShouldNotAutoConfigureRelatedBeans() { + void existingResourceConfigBeanShouldNotAutoConfigureRelatedBeans() { this.contextRunner.withUserConfiguration(ConfigWithResourceConfig.class).run((context) -> { assertThat(context).hasSingleBean(ResourceConfig.class); assertThat(context).doesNotHaveBean(JerseyApplicationPath.class); @@ -98,7 +98,7 @@ public void existingResourceConfigBeanShouldNotAutoConfigureRelatedBeans() { @Test @SuppressWarnings("unchecked") - public void servletRegistrationBeanIsAutoConfiguredWhenNeeded() { + void servletRegistrationBeanIsAutoConfiguredWhenNeeded() { this.contextRunner.withPropertyValues("spring.jersey.application-path=/jersey").run((context) -> { ServletRegistrationBean bean = context.getBean(ServletRegistrationBean.class); assertThat(bean.getUrlMappings()).containsExactly("/jersey/*"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java index 5d7c37b26a2a..07e7e93b8994 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJdbcTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.autoconfigure.batch; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.batch.core.configuration.annotation.BatchConfigurer; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; @@ -29,7 +29,7 @@ import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; @@ -41,7 +41,7 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("spring-jdbc-*.jar") class BatchAutoConfigurationWithoutJdbcTests { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java index 6bc5790be7ca..79c7a1f8ff2f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java @@ -18,8 +18,8 @@ import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; @@ -34,7 +34,7 @@ import org.springframework.boot.jdbc.DataSourceInitializationMode; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; @@ -45,15 +45,15 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("hibernate-jpa-*.jar") -public class BatchAutoConfigurationWithoutJpaTests { +class BatchAutoConfigurationWithoutJpaTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); @Test - public void jdbcWithDefaultSettings() { + void jdbcWithDefaultSettings() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.generate-unique-name=true").run((context) -> { assertThat(context).hasSingleBean(JobLauncher.class); @@ -73,7 +73,7 @@ public void jdbcWithDefaultSettings() { } @Test - public void jdbcWithCustomPrefix() { + void jdbcWithCustomPrefix() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.batch.schema:classpath:batch/custom-schema-hsql.sql", diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index 438bca9fca54..09a13d4d17b9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -40,8 +40,8 @@ import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.jcache.embedded.JCachingProvider; import org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -50,7 +50,7 @@ import org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration; import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; @@ -87,38 +87,38 @@ * @author Mark Paluch * @author Ryon Day */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("hazelcast-client-*.jar") -public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { +class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test - public void noEnableCaching() { + void noEnableCaching() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test - public void cacheManagerBackOff() { + void cacheManagerBackOff() { this.contextRunner.withUserConfiguration(CustomCacheManagerConfiguration.class) .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) .containsOnly("custom1")); } @Test - public void cacheManagerFromSupportBackOff() { + void cacheManagerFromSupportBackOff() { this.contextRunner.withUserConfiguration(CustomCacheManagerFromSupportConfiguration.class) .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) .containsOnly("custom1")); } @Test - public void cacheResolverFromSupportBackOff() { + void cacheResolverFromSupportBackOff() { this.contextRunner.withUserConfiguration(CustomCacheResolverFromSupportConfiguration.class) .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test - public void customCacheResolverCanBeDefined() { + void customCacheResolverCanBeDefined() { this.contextRunner.withUserConfiguration(SpecificCacheResolverConfiguration.class) .withPropertyValues("spring.cache.type=simple").run((context) -> { getCacheManager(context, ConcurrentMapCacheManager.class); @@ -127,7 +127,7 @@ public void customCacheResolverCanBeDefined() { } @Test - public void notSupportedCachingMode() { + void notSupportedCachingMode() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=foobar") .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) @@ -135,7 +135,7 @@ public void notSupportedCachingMode() { } @Test - public void simpleCacheExplicit() { + void simpleCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=simple") .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) @@ -143,14 +143,14 @@ public void simpleCacheExplicit() { } @Test - public void simpleCacheWithCustomizers() { + void simpleCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "simple") .run(verifyCustomizers("allCacheManagerCustomizer", "simpleCacheManagerCustomizer")); } @Test - public void simpleCacheExplicitWithCacheNames() { + void simpleCacheExplicitWithCacheNames() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") @@ -161,7 +161,7 @@ public void simpleCacheExplicitWithCacheNames() { } @Test - public void genericCacheWithCaches() { + void genericCacheWithCaches() { this.contextRunner.withUserConfiguration(GenericCacheConfiguration.class).run((context) -> { SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); assertThat(cacheManager.getCache("first")).isEqualTo(context.getBean("firstCache")); @@ -171,7 +171,7 @@ public void genericCacheWithCaches() { } @Test - public void genericCacheExplicit() { + void genericCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=generic") .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) @@ -180,14 +180,14 @@ public void genericCacheExplicit() { } @Test - public void genericCacheWithCustomizers() { + void genericCacheWithCustomizers() { this.contextRunner.withUserConfiguration(GenericCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "generic") .run(verifyCustomizers("allCacheManagerCustomizer", "genericCacheManagerCustomizer")); } @Test - public void genericCacheExplicitWithCaches() { + void genericCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(GenericCacheConfiguration.class) .withPropertyValues("spring.cache.type=generic").run((context) -> { SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); @@ -198,7 +198,7 @@ public void genericCacheExplicitWithCaches() { } @Test - public void couchbaseCacheExplicit() { + void couchbaseCacheExplicit() { this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.class) .withPropertyValues("spring.cache.type=couchbase").run((context) -> { CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); @@ -207,14 +207,14 @@ public void couchbaseCacheExplicit() { } @Test - public void couchbaseCacheWithCustomizers() { + void couchbaseCacheWithCustomizers() { this.contextRunner.withUserConfiguration(CouchbaseCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "couchbase") .run(verifyCustomizers("allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer")); } @Test - public void couchbaseCacheExplicitWithCaches() { + void couchbaseCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.class) .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") @@ -229,7 +229,7 @@ public void couchbaseCacheExplicitWithCaches() { } @Test - public void couchbaseCacheExplicitWithTtl() { + void couchbaseCacheExplicitWithTtl() { this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.class) .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", "spring.cache.couchbase.expiration=2000") @@ -244,7 +244,7 @@ public void couchbaseCacheExplicitWithTtl() { } @Test - public void redisCacheExplicit() { + void redisCacheExplicit() { this.contextRunner.withUserConfiguration(RedisConfiguration.class) .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", "spring.cache.redis.cacheNullValues=false", "spring.cache.redis.keyPrefix=prefix", @@ -261,7 +261,7 @@ public void redisCacheExplicit() { } @Test - public void redisCacheWithRedisCacheConfiguration() { + void redisCacheWithRedisCacheConfiguration() { this.contextRunner.withUserConfiguration(RedisWithCacheConfigurationConfiguration.class) .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", "spring.cache.redis.keyPrefix=foo") @@ -275,7 +275,7 @@ public void redisCacheWithRedisCacheConfiguration() { } @Test - public void redisCacheWithRedisCacheManagerBuilderCustomizer() { + void redisCacheWithRedisCacheManagerBuilderCustomizer() { this.contextRunner.withUserConfiguration(RedisWithRedisCacheManagerBuilderCustomizerConfiguration.class) .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000") .run((context) -> { @@ -286,14 +286,14 @@ public void redisCacheWithRedisCacheManagerBuilderCustomizer() { } @Test - public void redisCacheWithCustomizers() { + void redisCacheWithCustomizers() { this.contextRunner.withUserConfiguration(RedisWithCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "redis") .run(verifyCustomizers("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); } @Test - public void redisCacheExplicitWithCaches() { + void redisCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(RedisConfiguration.class).withPropertyValues("spring.cache.type=redis", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar").run((context) -> { RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); @@ -307,7 +307,7 @@ public void redisCacheExplicitWithCaches() { } @Test - public void noOpCacheExplicit() { + void noOpCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=none").run((context) -> { NoOpCacheManager cacheManager = getCacheManager(context, NoOpCacheManager.class); @@ -316,7 +316,7 @@ public void noOpCacheExplicit() { } @Test - public void jCacheCacheNoProviderExplicit() { + void jCacheCacheNoProviderExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache") .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) @@ -325,7 +325,7 @@ public void jCacheCacheNoProviderExplicit() { } @Test - public void jCacheCacheWithProvider() { + void jCacheCacheWithProvider() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) @@ -338,7 +338,7 @@ public void jCacheCacheWithProvider() { } @Test - public void jCacheCacheWithCaches() { + void jCacheCacheWithCaches() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, @@ -350,7 +350,7 @@ public void jCacheCacheWithCaches() { } @Test - public void jCacheCacheWithCachesAndCustomConfig() { + void jCacheCacheWithCachesAndCustomConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, @@ -366,7 +366,7 @@ public void jCacheCacheWithCachesAndCustomConfig() { } @Test - public void jCacheCacheWithExistingJCacheManager() { + void jCacheCacheWithExistingJCacheManager() { this.contextRunner.withUserConfiguration(JCacheCustomCacheManager.class) .withPropertyValues("spring.cache.type=jcache").run((context) -> { JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); @@ -375,7 +375,7 @@ public void jCacheCacheWithExistingJCacheManager() { } @Test - public void jCacheCacheWithUnknownProvider() { + void jCacheCacheWithUnknownProvider() { String wrongCachingProviderClassName = "org.acme.FooBar"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", @@ -385,7 +385,7 @@ public void jCacheCacheWithUnknownProvider() { } @Test - public void jCacheCacheWithConfig() { + void jCacheCacheWithConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) @@ -399,7 +399,7 @@ public void jCacheCacheWithConfig() { } @Test - public void jCacheCacheWithWrongConfig() { + void jCacheCacheWithWrongConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/cache/does-not-exist.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) @@ -410,7 +410,7 @@ public void jCacheCacheWithWrongConfig() { } @Test - public void jCacheCacheUseBeanClassLoader() { + void jCacheCacheUseBeanClassLoader() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) @@ -421,7 +421,7 @@ public void jCacheCacheUseBeanClassLoader() { } @Test - public void hazelcastCacheExplicit() { + void hazelcastCacheExplicit() { this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) .withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { @@ -435,14 +435,14 @@ public void hazelcastCacheExplicit() { } @Test - public void hazelcastCacheWithCustomizers() { + void hazelcastCacheWithCustomizers() { this.contextRunner.withUserConfiguration(HazelcastCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "hazelcast") .run(verifyCustomizers("allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer")); } @Test - public void hazelcastCacheWithExistingHazelcastInstance() { + void hazelcastCacheWithExistingHazelcastInstance() { this.contextRunner.withUserConfiguration(HazelcastCustomHazelcastInstance.class) .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); @@ -452,7 +452,7 @@ public void hazelcastCacheWithExistingHazelcastInstance() { } @Test - public void hazelcastCacheWithHazelcastAutoConfiguration() { + void hazelcastCacheWithHazelcastAutoConfiguration() { String hazelcastConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) .withUserConfiguration(DefaultCacheConfiguration.class) @@ -469,7 +469,7 @@ public void hazelcastCacheWithHazelcastAutoConfiguration() { } @Test - public void hazelcastAsJCacheWithCaches() { + void hazelcastAsJCacheWithCaches() { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); try { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) @@ -488,7 +488,7 @@ public void hazelcastAsJCacheWithCaches() { } @Test - public void hazelcastAsJCacheWithConfig() { + void hazelcastAsJCacheWithConfig() { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); try { String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; @@ -509,7 +509,7 @@ public void hazelcastAsJCacheWithConfig() { } @Test - public void hazelcastAsJCacheWithExistingHazelcastInstance() { + void hazelcastAsJCacheWithExistingHazelcastInstance() { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) .withUserConfiguration(DefaultCacheConfiguration.class) @@ -528,7 +528,7 @@ public void hazelcastAsJCacheWithExistingHazelcastInstance() { } @Test - public void infinispanCacheWithConfig() { + void infinispanCacheWithConfig() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml") .run((context) -> { @@ -539,14 +539,14 @@ public void infinispanCacheWithConfig() { } @Test - public void infinispanCacheWithCustomizers() { + void infinispanCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "infinispan") .run(verifyCustomizers("allCacheManagerCustomizer", "infinispanCacheManagerCustomizer")); } @Test - public void infinispanCacheWithCaches() { + void infinispanCacheWithCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") @@ -555,7 +555,7 @@ public void infinispanCacheWithCaches() { } @Test - public void infinispanCacheWithCachesAndCustomConfig() { + void infinispanCacheWithCachesAndCustomConfig() { this.contextRunner.withUserConfiguration(InfinispanCustomConfiguration.class) .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") @@ -567,7 +567,7 @@ public void infinispanCacheWithCachesAndCustomConfig() { } @Test - public void infinispanAsJCacheWithCaches() { + void infinispanAsJCacheWithCaches() { String cachingProviderClassName = JCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", @@ -578,7 +578,7 @@ public void infinispanAsJCacheWithCaches() { } @Test - public void infinispanAsJCacheWithConfig() { + void infinispanAsJCacheWithConfig() { String cachingProviderClassName = JCachingProvider.class.getName(); String configLocation = "infinispan.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) @@ -593,7 +593,7 @@ public void infinispanAsJCacheWithConfig() { } @Test - public void jCacheCacheWithCachesAndCustomizer() { + void jCacheCacheWithCachesAndCustomizer() { String cachingProviderClassName = HazelcastCachingProvider.class.getName(); try { this.contextRunner.withUserConfiguration(JCacheWithCustomizerConfiguration.class) @@ -611,7 +611,7 @@ public void jCacheCacheWithCachesAndCustomizer() { } @Test - public void caffeineCacheWithExplicitCaches() { + void caffeineCacheWithExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo").run((context) -> { CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); @@ -624,21 +624,21 @@ public void caffeineCacheWithExplicitCaches() { } @Test - public void caffeineCacheWithCustomizers() { + void caffeineCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "caffeine") .run(verifyCustomizers("allCacheManagerCustomizer", "caffeineCacheManagerCustomizer")); } @Test - public void caffeineCacheWithExplicitCacheBuilder() { + void caffeineCacheWithExplicitCacheBuilder() { this.contextRunner.withUserConfiguration(CaffeineCacheBuilderConfiguration.class) .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") .run(this::validateCaffeineCacheWithStats); } @Test - public void caffeineCacheExplicitWithSpec() { + void caffeineCacheExplicitWithSpec() { this.contextRunner.withUserConfiguration(CaffeineCacheSpecConfiguration.class) .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") @@ -646,7 +646,7 @@ public void caffeineCacheExplicitWithSpec() { } @Test - public void caffeineCacheExplicitWithSpecString() { + void caffeineCacheExplicitWithSpecString() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") @@ -654,7 +654,7 @@ public void caffeineCacheExplicitWithSpecString() { } @Test - public void autoConfiguredCacheManagerCanBeSwapped() { + void autoConfiguredCacheManagerCanBeSwapped() { this.contextRunner.withUserConfiguration(CacheManagerPostProcessorConfiguration.class) .withPropertyValues("spring.cache.type=caffeine").run((context) -> { getCacheManager(context, SimpleCacheManager.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java index 3a21100a9fd1..bf06b9b4f357 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache2CacheAutoConfigurationTests.java @@ -16,8 +16,8 @@ package org.springframework.boot.autoconfigure.cache; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.cache.CacheAutoConfigurationTests.DefaultCacheAndCustomizersConfiguration; @@ -25,7 +25,7 @@ import org.springframework.boot.autoconfigure.cache.CacheAutoConfigurationTests.EhCacheCustomCacheManager; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.cache.ehcache.EhCacheCacheManager; import static org.assertj.core.api.Assertions.assertThat; @@ -36,15 +36,15 @@ * @author Stephane Nicoll * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("ehcache-3*.jar") -public class EhCache2CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { +class EhCache2CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); @Test - public void ehCacheWithCaches() { + void ehCacheWithCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=ehcache").run((context) -> { EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); @@ -55,14 +55,14 @@ public void ehCacheWithCaches() { } @Test - public void ehCacheWithCustomizers() { + void ehCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) .withPropertyValues("spring.cache.type=" + "ehcache") .run(verifyCustomizers("allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer")); } @Test - public void ehCacheWithConfig() { + void ehCacheWithConfig() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=ehcache", "spring.cache.ehcache.config=cache/ehcache-override.xml") @@ -73,7 +73,7 @@ public void ehCacheWithConfig() { } @Test - public void ehCacheWithExistingCacheManager() { + void ehCacheWithExistingCacheManager() { this.contextRunner.withUserConfiguration(EhCacheCustomCacheManager.class) .withPropertyValues("spring.cache.type=ehcache").run((context) -> { EhCacheCacheManager cacheManager = getCacheManager(context, EhCacheCacheManager.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java index 172e9bebf8b8..987207733a3f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java @@ -17,12 +17,12 @@ package org.springframework.boot.autoconfigure.cache; import org.ehcache.jsr107.EhcacheCachingProvider; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.cache.CacheAutoConfigurationTests.DefaultCacheConfiguration; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @@ -35,12 +35,12 @@ * @author Stephane Nicoll * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("ehcache-2*.jar") -public class EhCache3CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { +class EhCache3CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test - public void ehcache3AsJCacheWithCaches() { + void ehcache3AsJCacheWithCaches() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, @@ -52,7 +52,7 @@ public void ehcache3AsJCacheWithCaches() { } @Test - public void ehcache3AsJCacheWithConfig() { + void ehcache3AsJCacheWithConfig() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java index 7d97813a3512..08aebcd68263 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java @@ -16,14 +16,13 @@ package org.springframework.boot.autoconfigure.condition; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.cache.caffeine.CaffeineCacheManager; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,22 +35,16 @@ * @author Stephane Nicoll * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("spring-context-support-*.jar") -public class ConditionalOnMissingBeanWithFilteredClasspathTests { +class ConditionalOnMissingBeanWithFilteredClasspathTests { - private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - - @After - public void closeContext() { - this.context.close(); - } + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(OnBeanTypeConfiguration.class); @Test - public void testNameOnMissingBeanTypeWithMissingImport() { - this.context.register(OnBeanTypeConfiguration.class); - this.context.refresh(); - assertThat(this.context.containsBean("foo")).isTrue(); + void testNameOnMissingBeanTypeWithMissingImport() { + this.contextRunner.run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java index fa30238ad543..2286d6fbaaec 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java @@ -17,12 +17,12 @@ package org.springframework.boot.autoconfigure.condition; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.condition.OnBeanCondition.BeanTypeDeductionException; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -38,12 +38,12 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("jackson-core-*.jar") -public class OnBeanConditionTypeDeductionFailureTests { +class OnBeanConditionTypeDeductionFailureTests { @Test - public void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() { + void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() { assertThatExceptionOfType(Exception.class) .isThrownBy(() -> new AnnotationConfigApplicationContext(ImportingConfiguration.class).close()) .satisfies((ex) -> { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java index d012fb660ed0..2a32d7a853fb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java @@ -16,15 +16,15 @@ package org.springframework.boot.autoconfigure.data.redis; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration.JedisClientConfigurationBuilder; @@ -38,15 +38,15 @@ * @author Mark Paluch * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("lettuce-core-*.jar") -public class RedisAutoConfigurationJedisTests { +class RedisAutoConfigurationJedisTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test - public void testOverrideRedisConfiguration() { + void testOverrideRedisConfiguration() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.database:1").run((context) -> { JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); @@ -57,7 +57,7 @@ public void testOverrideRedisConfiguration() { } @Test - public void testCustomizeRedisConfiguration() { + void testCustomizeRedisConfiguration() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); assertThat(cf.isUseSsl()).isTrue(); @@ -65,7 +65,7 @@ public void testCustomizeRedisConfiguration() { } @Test - public void testRedisUrlConfiguration() { + void testRedisUrlConfiguration() { this.contextRunner .withPropertyValues("spring.redis.host:foo", "spring.redis.url:redis://user:password@example:33") .run((context) -> { @@ -78,7 +78,7 @@ public void testRedisUrlConfiguration() { } @Test - public void testOverrideUrlRedisConfiguration() { + void testOverrideUrlRedisConfiguration() { this.contextRunner .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", "spring.redis.port:1000", "spring.redis.ssl:false", "spring.redis.url:rediss://user:password@example:33") @@ -92,7 +92,7 @@ public void testOverrideUrlRedisConfiguration() { } @Test - public void testPasswordInUrlWithColon() { + void testPasswordInUrlWithColon() { this.contextRunner.withPropertyValues("spring.redis.url:redis://:pass:word@example:33").run((context) -> { assertThat(context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("example"); assertThat(context.getBean(JedisConnectionFactory.class).getPort()).isEqualTo(33); @@ -101,7 +101,7 @@ public void testPasswordInUrlWithColon() { } @Test - public void testPasswordInUrlStartsWithColon() { + void testPasswordInUrlStartsWithColon() { this.contextRunner.withPropertyValues("spring.redis.url:redis://user::pass:word@example:33").run((context) -> { assertThat(context.getBean(JedisConnectionFactory.class).getHostName()).isEqualTo("example"); assertThat(context.getBean(JedisConnectionFactory.class).getPort()).isEqualTo(33); @@ -110,7 +110,7 @@ public void testPasswordInUrlStartsWithColon() { } @Test - public void testRedisConfigurationWithPool() { + void testRedisConfigurationWithPool() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.jedis.pool.min-idle:1", "spring.redis.jedis.pool.max-idle:4", "spring.redis.jedis.pool.max-active:16", "spring.redis.jedis.pool.max-wait:2000", "spring.redis.jedis.pool.time-between-eviction-runs:30000") @@ -126,7 +126,7 @@ public void testRedisConfigurationWithPool() { } @Test - public void testRedisConfigurationWithTimeout() { + void testRedisConfigurationWithTimeout() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.timeout:100").run((context) -> { JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); @@ -135,7 +135,7 @@ public void testRedisConfigurationWithTimeout() { } @Test - public void testRedisConfigurationWithClientName() { + void testRedisConfigurationWithClientName() { this.contextRunner.withPropertyValues("spring.redis.host:foo", "spring.redis.client-name:spring-boot") .run((context) -> { JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); @@ -145,7 +145,7 @@ public void testRedisConfigurationWithClientName() { } @Test - public void testRedisConfigurationWithSentinel() { + void testRedisConfigurationWithSentinel() { this.contextRunner .withPropertyValues("spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") @@ -156,7 +156,7 @@ public void testRedisConfigurationWithSentinel() { } @Test - public void testRedisConfigurationWithSentinelAndPassword() { + void testRedisConfigurationWithSentinelAndPassword() { this.contextRunner .withPropertyValues("spring.redis.password=password", "spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") @@ -168,7 +168,7 @@ public void testRedisConfigurationWithSentinelAndPassword() { } @Test - public void testRedisConfigurationWithCluster() { + void testRedisConfigurationWithCluster() { this.contextRunner.withPropertyValues("spring.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380") .run((context) -> assertThat(context.getBean(JedisConnectionFactory.class).getClusterConnection()) .isNotNull()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java index dfd1666be5d5..caba6b045cc4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationWithoutJacksonTests.java @@ -16,14 +16,14 @@ package org.springframework.boot.autoconfigure.hateoas; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext; import org.springframework.mock.web.MockServletContext; @@ -32,14 +32,14 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("jackson-*.jar") -public class HypermediaAutoConfigurationWithoutJacksonTests { +class HypermediaAutoConfigurationWithoutJacksonTests { private AnnotationConfigServletWebApplicationContext context; @Test - public void jacksonRelatedConfigurationBacksOff() { + void jacksonRelatedConfigurationBacksOff() { this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(BaseConfig.class); this.context.setServletContext(new MockServletContext()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java index 8d7c184fdf65..8f55c51db375 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java @@ -22,8 +22,8 @@ import com.hazelcast.config.QueueConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -31,7 +31,7 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ContextConsumer; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @@ -43,15 +43,15 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("hazelcast-client-*.jar") -public class HazelcastAutoConfigurationServerTests { +class HazelcastAutoConfigurationServerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test - public void defaultConfigFile() { + void defaultConfigFile() { // hazelcast.xml present in root classpath this.contextRunner.run((context) -> { Config config = context.getBean(HazelcastInstance.class).getConfig(); @@ -60,7 +60,7 @@ public void defaultConfigFile() { } @Test - public void systemPropertyWithXml() { + void systemPropertyWithXml() { this.contextRunner .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") @@ -71,7 +71,7 @@ public void systemPropertyWithXml() { } @Test - public void systemPropertyWithYaml() { + void systemPropertyWithYaml() { this.contextRunner .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml") @@ -82,7 +82,7 @@ public void systemPropertyWithYaml() { } @Test - public void explicitConfigFileWithXml() { + void explicitConfigFileWithXml() { this.contextRunner .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.xml") @@ -91,7 +91,7 @@ public void explicitConfigFileWithXml() { } @Test - public void explicitConfigFileWithYaml() { + void explicitConfigFileWithYaml() { this.contextRunner .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.yaml") @@ -100,7 +100,7 @@ public void explicitConfigFileWithYaml() { } @Test - public void explicitConfigUrlWithXml() { + void explicitConfigUrlWithXml() { this.contextRunner .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + "boot/autoconfigure/hazelcast/hazelcast-specific.xml") @@ -109,7 +109,7 @@ public void explicitConfigUrlWithXml() { } @Test - public void explicitConfigUrlWithYaml() { + void explicitConfigUrlWithYaml() { this.contextRunner .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + "boot/autoconfigure/hazelcast/hazelcast-specific.yaml") @@ -125,14 +125,14 @@ private ContextConsumer assertSpecificHazelcastSer } @Test - public void unknownConfigFile() { + void unknownConfigFile() { this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("foo/bar/unknown.xml")); } @Test - public void configInstanceWithName() { + void configInstanceWithName() { Config config = new Config("my-test-instance"); HazelcastInstance existing = Hazelcast.newHazelcastInstance(config); try { @@ -150,7 +150,7 @@ public void configInstanceWithName() { } @Test - public void configInstanceWithoutName() { + void configInstanceWithoutName() { this.contextRunner.withUserConfiguration(HazelcastConfigNoName.class) .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> { Config config = context.getBean(HazelcastInstance.class).getConfig(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java index 6859d5a5682a..0300234a1ae4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java @@ -16,13 +16,13 @@ package org.springframework.boot.autoconfigure.http; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +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.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -32,24 +32,16 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("jackson-*.jar") -public class HttpMessageConvertersAutoConfigurationWithoutJacksonTests { +class HttpMessageConvertersAutoConfigurationWithoutJacksonTests { - private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); @Test - public void autoConfigurationWorksWithSpringHateoasButWithoutJackson() { - this.context.register(HttpMessageConvertersAutoConfiguration.class); - this.context.refresh(); - assertThat(this.context.getBeansOfType(HttpMessageConverters.class)).hasSize(1); + void autoConfigurationWorksWithSpringHateoasButWithoutJackson() { + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HttpMessageConverters.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java index 609ea8fda936..e91db04462c5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzerTests.java @@ -16,14 +16,14 @@ package org.springframework.boot.autoconfigure.jdbc; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.mock.env.MockEnvironment; @@ -36,14 +36,14 @@ * @author Andy Wilkinson * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions({ "h2-*.jar", "hsqldb-*.jar" }) -public class DataSourceBeanCreationFailureAnalyzerTests { +class DataSourceBeanCreationFailureAnalyzerTests { private final MockEnvironment environment = new MockEnvironment(); @Test - public void failureAnalysisIsPerformed() { + void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); assertThat(failureAnalysis.getDescription()).contains("'url' attribute is not specified", "no embedded datasource could be configured", "Failed to determine a suitable driver class"); @@ -54,7 +54,7 @@ public void failureAnalysisIsPerformed() { } @Test - public void failureAnalysisIsPerformedWithActiveProfiles() { + void failureAnalysisIsPerformedWithActiveProfiles() { this.environment.setActiveProfiles("first", "second"); FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); assertThat(failureAnalysis.getAction()).contains("(the profiles first,second are currently active)"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java index b718fe3a93ff..675c3001766b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java @@ -18,13 +18,13 @@ import javax.json.bind.Jsonb; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +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.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -33,15 +33,15 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("johnzon-jsonb-*.jar") -public class JsonbAutoConfigurationWithNoProviderTests { +class JsonbAutoConfigurationWithNoProviderTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); @Test - public void jsonbBacksOffWhenThereIsNoProvider() { + void jsonbBacksOffWhenThereIsNoProvider() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Jsonb.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java index bb35f8ef77dd..de7eea09226a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java @@ -17,15 +17,15 @@ package org.springframework.boot.autoconfigure.orm.jpa; import org.ehcache.jsr107.EhcacheCachingProvider; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Configuration; @@ -36,9 +36,9 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("ehcache-2*.jar") -public class Hibernate2ndLevelCacheIntegrationTests { +class Hibernate2ndLevelCacheIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, DataSourceAutoConfiguration.class, @@ -47,7 +47,7 @@ public class Hibernate2ndLevelCacheIntegrationTests { .withUserConfiguration(TestConfiguration.class); @Test - public void hibernate2ndLevelCacheWithJCacheAndEhCache3() { + void hibernate2ndLevelCacheWithJCacheAndEhCache3() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; this.contextRunner diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java index dac00cb2de07..d614a3604988 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java @@ -16,13 +16,13 @@ package org.springframework.boot.autoconfigure.session; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.session.web.http.DefaultCookieSerializer; import static org.assertj.core.api.Assertions.assertThat; @@ -33,15 +33,15 @@ * * @author Vedran Pavic */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("spring-security-*") -public class SessionAutoConfigurationWithoutSecurityTests extends AbstractSessionAutoConfigurationTests { +class SessionAutoConfigurationWithoutSecurityTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test - public void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { + void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class).run((context) -> { DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); assertThat(cookieSerializer).hasFieldOrPropertyWithValue("rememberMeRequestAttribute", null); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java index 502f1c1777b7..969b65795d15 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java @@ -18,13 +18,13 @@ import javax.validation.Validator; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +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.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; import static org.assertj.core.api.Assertions.assertThat; @@ -35,24 +35,19 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions({ "tomcat-embed-el-*.jar", "el-api-*.jar" }) -public class ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests { +class ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests { - private AnnotationConfigApplicationContext context; - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test - public void missingElDependencyIsTolerated() { - this.context = new AnnotationConfigApplicationContext(ValidationAutoConfiguration.class); - assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); + void missingElDependencyIsTolerated() { + this.contextRunner.run((context) -> { + assertThat(context).hasSingleBean(Validator.class); + assertThat(context).hasSingleBean(MethodValidationPostProcessor.class); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java index b25bf16389c7..8c07385f4f90 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java @@ -18,13 +18,13 @@ import javax.validation.Validator; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +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.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; import static org.assertj.core.api.Assertions.assertThat; @@ -34,24 +34,19 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("hibernate-validator-*.jar") -public class ValidationAutoConfigurationWithoutValidatorTests { +class ValidationAutoConfigurationWithoutValidatorTests { - private AnnotationConfigApplicationContext context; - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test - public void validationIsDisabled() { - this.context = new AnnotationConfigApplicationContext(ValidationAutoConfiguration.class); - assertThat(this.context.getBeansOfType(Validator.class)).isEmpty(); - assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class)).isEmpty(); + void validationIsDisabled() { + this.contextRunner.run((context) -> { + assertThat(context).doesNotHaveBean(Validator.class); + assertThat(context).doesNotHaveBean(MethodValidationPostProcessor.class); + }); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java index 15d8a7b89565..b5d3cf9dee08 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsEmbeddedDataSourceAutoConfigurationTests.java @@ -21,12 +21,12 @@ import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.ConfigurableApplicationContext; import static org.mockito.Mockito.never; @@ -37,12 +37,12 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("HikariCP-*.jar") -public class DevToolsEmbeddedDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { +class DevToolsEmbeddedDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { @Test - public void autoConfiguredDataSourceIsNotShutdown() throws SQLException { + void autoConfiguredDataSourceIsNotShutdown() throws SQLException { ConfigurableApplicationContext context = createContext(DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java index 1f05f7261931..3435063cd58e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java @@ -18,15 +18,15 @@ import javax.sql.DataSource; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -40,16 +40,16 @@ * @author Stephane Nicoll * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions({ "h2-*.jar", "hsqldb-*.jar", "derby-*.jar" }) -public class TestDatabaseAutoConfigurationNoEmbeddedTests { +class TestDatabaseAutoConfigurationNoEmbeddedTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(ExistingDataSourceConfiguration.class) .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test - public void applyAnyReplace() { + void applyAnyReplace() { this.contextRunner.run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) .hasMessageContaining("Failed to replace DataSource with an embedded database for tests.") .hasMessageContaining("If you want an embedded database please put a supported one on the classpath") @@ -57,7 +57,7 @@ public void applyAnyReplace() { } @Test - public void applyNoReplace() { + void applyNoReplace() { this.contextRunner.withPropertyValues("spring.test.database.replace=NONE").run((context) -> { assertThat(context).hasSingleBean(DataSource.class); assertThat(context).getBean(DataSource.class).isSameAs(context.getBean("myCustomDataSource")); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java index c4e1d79454a5..09ba31463e93 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithComponentIntegrationTests.java @@ -16,12 +16,10 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import static org.assertj.core.api.Assertions.assertThat; @@ -33,12 +31,8 @@ * * @author Phillip Webb */ -@RunWith(SpringRunner.class) @RestClientTest(ExampleRestClient.class) -public class RestClientTestWithComponentIntegrationTests { - - // JUnit 4 because RestClientTestWithoutJacksonIntegrationTests uses - // ModifiedClassPathRunner +class RestClientTestWithComponentIntegrationTests { @Autowired private MockRestServiceServer server; @@ -47,7 +41,7 @@ public class RestClientTestWithComponentIntegrationTests { private ExampleRestClient client; @Test - public void mockServerCall() { + void mockServerCall() { this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client.test()).isEqualTo("hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java index b2e89629da10..430f7492a970 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithoutJacksonIntegrationTests.java @@ -16,33 +16,43 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Test; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; /** * Tests for {@link RestClientTest @RestClientTest} without Jackson. * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("jackson-*.jar") -public class RestClientTestWithoutJacksonIntegrationTests { +@RestClientTest(ExampleRestClient.class) +class RestClientTestWithoutJacksonIntegrationTests { + + @Autowired + private MockRestServiceServer server; + + @Autowired + private ExampleRestClient client; @Test - public void restClientTestCanBeUsedWhenJacksonIsNotOnTheClassPath() { + void restClientTestCanBeUsedWhenJacksonIsNotOnTheClassPath() { assertThat(ClassUtils.isPresent("com.fasterxml.jackson.databind.Module", getClass().getClassLoader())) .isFalse(); - Result result = JUnitCore.runClasses(RestClientTestWithComponentIntegrationTests.class); - assertThat(result.getFailureCount()).isEqualTo(0); - assertThat(result.getRunCount()).isGreaterThan(0); + + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + assertThat(this.client.test()).isEqualTo("hello"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java index 4580c9f036a1..e09e252a4656 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java @@ -16,13 +16,14 @@ package org.springframework.boot.test.json; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.test.system.OutputCaptureRule; import org.springframework.boot.testsupport.runner.classpath.ClassPathOverrides; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -31,18 +32,23 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) +@ExtendWith(OutputCaptureExtension.class) @ClassPathOverrides("org.json:json:20140107") -public class DuplicateJsonObjectContextCustomizerFactoryTests { +class DuplicateJsonObjectContextCustomizerFactoryTests { - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); + private CapturedOutput capturedOutput; + + @BeforeEach + void setup(CapturedOutput capturedOutput) { + this.capturedOutput = capturedOutput; + } @Test - public void warningForMultipleVersions() { + void warningForMultipleVersions() { new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null).customizeContext(null, null); - assertThat(this.output.toString()) + assertThat(this.capturedOutput) .contains("Found multiple occurrences of org.json.JSONObject on the class path:"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml b/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml index 4d7e027f9155..72f28e1b1a6d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/pom.xml @@ -70,6 +70,10 @@ org.junit.jupiter junit-jupiter + + org.junit.platform + junit-platform-launcher + org.mockito mockito-core diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathExclusions.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathExclusions.java index 249d0eb252a6..dfb83d63f4cb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathExclusions.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathExclusions.java @@ -24,8 +24,8 @@ import java.lang.annotation.Target; /** - * Annotation used in combination with {@link ModifiedClassPathRunner} to exclude entries - * from the classpath. + * Annotation used in combination with {@link ModifiedClassPathExtension} to exclude + * entries from the classpath. * * @author Andy Wilkinson * @since 1.5.0 diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathOverrides.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathOverrides.java index 75fc689c61a4..67aee114d8c9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathOverrides.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ClassPathOverrides.java @@ -23,8 +23,8 @@ import java.lang.annotation.Target; /** - * Annotation used in combination with {@link ModifiedClassPathRunner} to override entries - * on the classpath. + * Annotation used in combination with {@link ModifiedClassPathExtension} to override + * entries on the classpath. * * @author Andy Wilkinson * @since 1.5.0 diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoader.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoader.java new file mode 100644 index 000000000000..f47ae15daa7e --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoader.java @@ -0,0 +1,46 @@ +/* + * 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.testsupport.runner.classpath; + +import java.net.URL; +import java.net.URLClassLoader; + +/** + * Custom {@link URLClassLoader} that modifies the class path. + * + * @author Andy Wilkinson + * @author Christoph Dreis + * @see ModifiedClassPathClassLoaderFactory + */ +final class ModifiedClassPathClassLoader extends URLClassLoader { + + private final ClassLoader junitLoader; + + ModifiedClassPathClassLoader(URL[] urls, ClassLoader parent, ClassLoader junitLoader) { + super(urls, parent); + this.junitLoader = junitLoader; + } + + @Override + public Class loadClass(String name) throws ClassNotFoundException { + if (name.startsWith("org.junit") || name.startsWith("org.hamcrest")) { + return this.junitLoader.loadClass(name); + } + return super.loadClass(name); + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoaderFactory.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoaderFactory.java new file mode 100644 index 000000000000..5a662827a0ae --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathClassLoaderFactory.java @@ -0,0 +1,249 @@ +/* + * 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.testsupport.runner.classpath; + +import java.io.File; +import java.lang.management.ManagementFactory; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import org.apache.maven.repository.internal.MavenRepositorySystemUtils; +import org.eclipse.aether.DefaultRepositorySystemSession; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.collection.CollectRequest; +import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; +import org.eclipse.aether.graph.Dependency; +import org.eclipse.aether.impl.DefaultServiceLocator; +import org.eclipse.aether.repository.LocalRepository; +import org.eclipse.aether.repository.RemoteRepository; +import org.eclipse.aether.resolution.ArtifactResult; +import org.eclipse.aether.resolution.DependencyRequest; +import org.eclipse.aether.resolution.DependencyResult; +import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; +import org.eclipse.aether.spi.connector.transport.TransporterFactory; +import org.eclipse.aether.transport.http.HttpTransporterFactory; + +import org.springframework.core.annotation.MergedAnnotation; +import org.springframework.core.annotation.MergedAnnotations; +import org.springframework.util.AntPathMatcher; +import org.springframework.util.StringUtils; + +/** + * A factory that creates a custom class loader with a modified class path that is used in + * {@link ModifiedClassPathExtension} to both load the test class and as the thread + * context class loader while the test is being run. + * + * @author Andy Wilkinson + * @author Christoph Dreis + * @see ModifiedClassPathClassLoader + * @see ModifiedClassPathExtension + */ +final class ModifiedClassPathClassLoaderFactory { + + private static final Pattern INTELLIJ_CLASSPATH_JAR_PATTERN = Pattern.compile(".*classpath(\\d+)?\\.jar"); + + private ModifiedClassPathClassLoaderFactory() { + } + + static URLClassLoader createTestClassLoader(Class testClass) { + ClassLoader classLoader = testClass.getClassLoader(); + return new ModifiedClassPathClassLoader(processUrls(extractUrls(classLoader), testClass), + classLoader.getParent(), classLoader); + } + + private static URL[] extractUrls(ClassLoader classLoader) { + List extractedUrls = new ArrayList<>(); + doExtractUrls(classLoader).forEach((URL url) -> { + if (isManifestOnlyJar(url)) { + extractedUrls.addAll(extractUrlsFromManifestClassPath(url)); + } + else { + extractedUrls.add(url); + } + }); + return extractedUrls.toArray(new URL[0]); + } + + private static Stream doExtractUrls(ClassLoader classLoader) { + if (classLoader instanceof URLClassLoader) { + return Stream.of(((URLClassLoader) classLoader).getURLs()); + } + return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) + .map(ModifiedClassPathClassLoaderFactory::toURL); + } + + private static URL toURL(String entry) { + try { + return new File(entry).toURI().toURL(); + } + catch (Exception ex) { + throw new IllegalArgumentException(ex); + } + } + + private static boolean isManifestOnlyJar(URL url) { + return isSurefireBooterJar(url) || isShortenedIntelliJJar(url); + } + + private static boolean isSurefireBooterJar(URL url) { + return url.getPath().contains("surefirebooter"); + } + + private static boolean isShortenedIntelliJJar(URL url) { + String urlPath = url.getPath(); + boolean isCandidate = INTELLIJ_CLASSPATH_JAR_PATTERN.matcher(urlPath).matches(); + if (isCandidate) { + try { + Attributes attributes = getManifestMainAttributesFromUrl(url); + String createdBy = attributes.getValue("Created-By"); + return createdBy != null && createdBy.contains("IntelliJ"); + } + catch (Exception ex) { + } + } + return false; + } + + private static List extractUrlsFromManifestClassPath(URL booterJar) { + List urls = new ArrayList<>(); + try { + for (String entry : getClassPath(booterJar)) { + urls.add(new URL(entry)); + } + } + catch (Exception ex) { + throw new RuntimeException(ex); + } + return urls; + } + + private static String[] getClassPath(URL booterJar) throws Exception { + Attributes attributes = getManifestMainAttributesFromUrl(booterJar); + return StringUtils.delimitedListToStringArray(attributes.getValue(Attributes.Name.CLASS_PATH), " "); + } + + private static Attributes getManifestMainAttributesFromUrl(URL url) throws Exception { + try (JarFile jarFile = new JarFile(new File(url.toURI()))) { + return jarFile.getManifest().getMainAttributes(); + } + } + + private static URL[] processUrls(URL[] urls, Class testClass) { + MergedAnnotations annotations = MergedAnnotations.from(testClass, MergedAnnotations.SearchStrategy.EXHAUSTIVE); + ClassPathEntryFilter filter = new ClassPathEntryFilter(annotations.get(ClassPathExclusions.class)); + List processedUrls = new ArrayList<>(); + List additionalUrls = getAdditionalUrls(annotations.get(ClassPathOverrides.class)); + processedUrls.addAll(additionalUrls); + for (URL url : urls) { + if (!filter.isExcluded(url)) { + processedUrls.add(url); + } + } + return processedUrls.toArray(new URL[0]); + } + + private static List getAdditionalUrls(MergedAnnotation annotation) { + if (!annotation.isPresent()) { + return Collections.emptyList(); + } + return resolveCoordinates(annotation.getStringArray(MergedAnnotation.VALUE)); + } + + private static List resolveCoordinates(String[] coordinates) { + DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils.newServiceLocator(); + serviceLocator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); + serviceLocator.addService(TransporterFactory.class, HttpTransporterFactory.class); + RepositorySystem repositorySystem = serviceLocator.getService(RepositorySystem.class); + DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); + LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); + session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); + CollectRequest collectRequest = new CollectRequest(null, Arrays.asList( + new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2").build())); + + collectRequest.setDependencies(createDependencies(coordinates)); + DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); + try { + DependencyResult result = repositorySystem.resolveDependencies(session, dependencyRequest); + List resolvedArtifacts = new ArrayList<>(); + for (ArtifactResult artifact : result.getArtifactResults()) { + resolvedArtifacts.add(artifact.getArtifact().getFile().toURI().toURL()); + } + return resolvedArtifacts; + } + catch (Exception ignored) { + return Collections.emptyList(); + + } + } + + private static List createDependencies(String[] allCoordinates) { + List dependencies = new ArrayList<>(); + for (String coordinate : allCoordinates) { + dependencies.add(new Dependency(new DefaultArtifact(coordinate), null)); + } + return dependencies; + } + + /** + * Filter for class path entries. + */ + private static final class ClassPathEntryFilter { + + private final List exclusions; + + private final AntPathMatcher matcher = new AntPathMatcher(); + + private ClassPathEntryFilter(MergedAnnotation annotation) { + this.exclusions = new ArrayList<>(); + this.exclusions.add("log4j-*.jar"); + if (annotation.isPresent()) { + this.exclusions.addAll(Arrays.asList(annotation.getStringArray(MergedAnnotation.VALUE))); + } + } + + private boolean isExcluded(URL url) { + if (!"file".equals(url.getProtocol())) { + return false; + } + String name; + try { + name = new File(url.toURI()).getName(); + } + catch (URISyntaxException ex) { + return false; + } + for (String exclusion : this.exclusions) { + if (this.matcher.match(exclusion, name)) { + return true; + } + } + return false; + } + + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java new file mode 100644 index 000000000000..8e661a6ed932 --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java @@ -0,0 +1,108 @@ +/* + * 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.testsupport.runner.classpath; + +import java.lang.reflect.Method; +import java.net.URLClassLoader; + +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; +import org.junit.platform.engine.discovery.DiscoverySelectors; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.LauncherDiscoveryRequest; +import org.junit.platform.launcher.TestPlan; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; +import org.junit.platform.launcher.listeners.SummaryGeneratingListener; +import org.junit.platform.launcher.listeners.TestExecutionSummary; + +import org.springframework.util.CollectionUtils; +import org.springframework.util.ReflectionUtils; + +/** + * A custom {@link Extension} that runs tests using a modified class path. Entries are + * excluded from the class path using {@link ClassPathExclusions @ClassPathExclusions} and + * overridden using {@link ClassPathOverrides @ClassPathOverrides} on the test class. A + * class loader is created with the customized class path and is used both to load the + * test class and as the thread context class loader while the test is being run. + * + * NOTE: As JUnit 5 doesn't support native class loader support yet, this extension + * executes the tests with the modified class loader via the {@link Launcher} facilities. + * While the original test results are swallowed, the test itself is still executed. + * + * @author Christoph Dreis + * @since 2.2.0 + */ +public class ModifiedClassPathExtension implements InvocationInterceptor { + + @Override + public void interceptTestMethod(Invocation invocation, ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) throws Throwable { + if (isModifiedClassPathClassLoader(extensionContext)) { + invocation.proceed(); + return; + } + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + URLClassLoader classLoader = ModifiedClassPathClassLoaderFactory + .createTestClassLoader(extensionContext.getRequiredTestClass()); + Thread.currentThread().setContextClassLoader(classLoader); + try { + swallowOriginalInvocation(invocation); + TestExecutionSummary summary = launchTests(invocationContext, extensionContext, classLoader); + if (!CollectionUtils.isEmpty(summary.getFailures())) { + throw summary.getFailures().get(0).getException(); + } + } + catch (Exception ex) { + throw ex; + } + finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + } + + private TestExecutionSummary launchTests(ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext, URLClassLoader classLoader) throws ClassNotFoundException { + Class testClass = classLoader.loadClass(extensionContext.getRequiredTestClass().getName()); + Method method = ReflectionUtils.findMethod(testClass, invocationContext.getExecutable().getName()); + LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() + .selectors(DiscoverySelectors.selectMethod(testClass, method)).build(); + Launcher launcher = LauncherFactory.create(); + TestPlan testPlan = launcher.discover(request); + SummaryGeneratingListener listener = new SummaryGeneratingListener(); + launcher.registerTestExecutionListeners(listener); + launcher.execute(testPlan); + return listener.getSummary(); + } + + private boolean isModifiedClassPathClassLoader(ExtensionContext extensionContext) { + return extensionContext.getRequiredTestClass().getClassLoader().getClass().getName() + .equals(ModifiedClassPathClassLoader.class.getName()); + } + + private void swallowOriginalInvocation(Invocation invocation) { + try { + invocation.proceed(); + } + catch (Throwable ignore) { + + } + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java index c66f06e8af4d..62cab7af6d0a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java @@ -16,48 +16,18 @@ package org.springframework.boot.testsupport.runner.classpath; -import java.io.File; import java.lang.annotation.Annotation; -import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; -import java.util.jar.Attributes; -import java.util.jar.JarFile; -import java.util.regex.Pattern; -import java.util.stream.Stream; -import org.apache.maven.repository.internal.MavenRepositorySystemUtils; -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.artifact.DefaultArtifact; -import org.eclipse.aether.collection.CollectRequest; -import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; -import org.eclipse.aether.graph.Dependency; -import org.eclipse.aether.impl.DefaultServiceLocator; -import org.eclipse.aether.repository.LocalRepository; -import org.eclipse.aether.repository.RemoteRepository; -import org.eclipse.aether.resolution.ArtifactResult; -import org.eclipse.aether.resolution.DependencyRequest; -import org.eclipse.aether.resolution.DependencyResult; -import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; -import org.eclipse.aether.spi.connector.transport.TransporterFactory; -import org.eclipse.aether.transport.http.HttpTransporterFactory; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.TestClass; -import org.springframework.core.annotation.MergedAnnotation; -import org.springframework.core.annotation.MergedAnnotations; -import org.springframework.core.annotation.MergedAnnotations.SearchStrategy; -import org.springframework.util.AntPathMatcher; -import org.springframework.util.StringUtils; - /** * A custom {@link BlockJUnit4ClassRunner} that runs tests using a modified class path. * Entries are excluded from the class path using @@ -68,11 +38,11 @@ * * @author Andy Wilkinson * @since 1.5.0 + * @deprecated since 2.2.0 in favor of {@link ModifiedClassPathExtension} */ +@Deprecated public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { - private static final Pattern INTELLIJ_CLASSPATH_JAR_PATTERN = Pattern.compile(".*classpath(\\d+)?\\.jar"); - public ModifiedClassPathRunner(Class testClass) throws InitializationError { super(testClass); } @@ -80,7 +50,7 @@ public ModifiedClassPathRunner(Class testClass) throws InitializationError { @Override protected TestClass createTestClass(Class testClass) { try { - ClassLoader classLoader = createTestClassLoader(testClass); + ClassLoader classLoader = ModifiedClassPathClassLoaderFactory.createTestClassLoader(testClass); return new ModifiedClassPathTestClass(classLoader, testClass.getName()); } catch (Exception ex) { @@ -95,171 +65,6 @@ protected Object createTest() throws Exception { .doWithModifiedClassPathThreadContextClassLoader(() -> ModifiedClassPathRunner.super.createTest()); } - private URLClassLoader createTestClassLoader(Class testClass) throws Exception { - ClassLoader classLoader = this.getClass().getClassLoader(); - return new ModifiedClassPathClassLoader(processUrls(extractUrls(classLoader), testClass), - classLoader.getParent(), classLoader); - } - - private URL[] extractUrls(ClassLoader classLoader) throws Exception { - List extractedUrls = new ArrayList<>(); - doExtractUrls(classLoader).forEach((URL url) -> { - if (isManifestOnlyJar(url)) { - extractedUrls.addAll(extractUrlsFromManifestClassPath(url)); - } - else { - extractedUrls.add(url); - } - }); - return extractedUrls.toArray(new URL[0]); - } - - private Stream doExtractUrls(ClassLoader classLoader) throws Exception { - if (classLoader instanceof URLClassLoader) { - return Stream.of(((URLClassLoader) classLoader).getURLs()); - } - return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(this::toURL); - } - - private URL toURL(String entry) { - try { - return new File(entry).toURI().toURL(); - } - catch (Exception ex) { - throw new IllegalArgumentException(ex); - } - } - - private boolean isManifestOnlyJar(URL url) { - return isSurefireBooterJar(url) || isShortenedIntelliJJar(url); - } - - private boolean isSurefireBooterJar(URL url) { - return url.getPath().contains("surefirebooter"); - } - - private boolean isShortenedIntelliJJar(URL url) { - String urlPath = url.getPath(); - boolean isCandidate = INTELLIJ_CLASSPATH_JAR_PATTERN.matcher(urlPath).matches(); - if (isCandidate) { - try { - Attributes attributes = getManifestMainAttributesFromUrl(url); - String createdBy = attributes.getValue("Created-By"); - return createdBy != null && createdBy.contains("IntelliJ"); - } - catch (Exception ex) { - } - } - return false; - } - - private List extractUrlsFromManifestClassPath(URL booterJar) { - List urls = new ArrayList<>(); - try { - for (String entry : getClassPath(booterJar)) { - urls.add(new URL(entry)); - } - } - catch (Exception ex) { - throw new RuntimeException(ex); - } - return urls; - } - - private String[] getClassPath(URL booterJar) throws Exception { - Attributes attributes = getManifestMainAttributesFromUrl(booterJar); - return StringUtils.delimitedListToStringArray(attributes.getValue(Attributes.Name.CLASS_PATH), " "); - } - - private Attributes getManifestMainAttributesFromUrl(URL url) throws Exception { - try (JarFile jarFile = new JarFile(new File(url.toURI()))) { - return jarFile.getManifest().getMainAttributes(); - } - } - - private URL[] processUrls(URL[] urls, Class testClass) throws Exception { - MergedAnnotations annotations = MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE); - ClassPathEntryFilter filter = new ClassPathEntryFilter(annotations.get(ClassPathExclusions.class)); - List processedUrls = new ArrayList<>(); - List additionalUrls = getAdditionalUrls(annotations.get(ClassPathOverrides.class)); - processedUrls.addAll(additionalUrls); - for (URL url : urls) { - if (!filter.isExcluded(url)) { - processedUrls.add(url); - } - } - return processedUrls.toArray(new URL[0]); - } - - private List getAdditionalUrls(MergedAnnotation annotation) throws Exception { - if (!annotation.isPresent()) { - return Collections.emptyList(); - } - return resolveCoordinates(annotation.getStringArray(MergedAnnotation.VALUE)); - } - - private List resolveCoordinates(String[] coordinates) throws Exception { - DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils.newServiceLocator(); - serviceLocator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); - serviceLocator.addService(TransporterFactory.class, HttpTransporterFactory.class); - RepositorySystem repositorySystem = serviceLocator.getService(RepositorySystem.class); - DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); - LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); - session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); - CollectRequest collectRequest = new CollectRequest(null, Arrays.asList( - new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2").build())); - - collectRequest.setDependencies(createDependencies(coordinates)); - DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); - DependencyResult result = repositorySystem.resolveDependencies(session, dependencyRequest); - List resolvedArtifacts = new ArrayList<>(); - for (ArtifactResult artifact : result.getArtifactResults()) { - resolvedArtifacts.add(artifact.getArtifact().getFile().toURI().toURL()); - } - return resolvedArtifacts; - } - - private List createDependencies(String[] allCoordinates) { - List dependencies = new ArrayList<>(); - for (String coordinate : allCoordinates) { - dependencies.add(new Dependency(new DefaultArtifact(coordinate), null)); - } - return dependencies; - } - - /** - * Filter for class path entries. - */ - private static final class ClassPathEntryFilter { - - private final List exclusions; - - private final AntPathMatcher matcher = new AntPathMatcher(); - - private ClassPathEntryFilter(MergedAnnotation annotation) throws Exception { - this.exclusions = new ArrayList<>(); - this.exclusions.add("log4j-*.jar"); - if (annotation.isPresent()) { - this.exclusions.addAll(Arrays.asList(annotation.getStringArray(MergedAnnotation.VALUE))); - } - } - - private boolean isExcluded(URL url) throws Exception { - if (!"file".equals(url.getProtocol())) { - return false; - } - String name = new File(url.toURI()).getName(); - for (String exclusion : this.exclusions) { - if (this.matcher.match(exclusion, name)) { - return true; - } - } - return false; - } - - } - /** * Custom {@link TestClass} that uses a modified class path. */ diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionExclusionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionExclusionsTests.java new file mode 100644 index 000000000000..a6fdcf1c3b4b --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionExclusionsTests.java @@ -0,0 +1,53 @@ +/* + * 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.testsupport.runner.classpath; + +import org.hamcrest.Matcher; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.isA; + +/** + * Tests for {@link ModifiedClassPathExtension} excluding entries from the class path. + * + * @author Christoph Dreis + */ +@ExtendWith(ModifiedClassPathExtension.class) +@ClassPathExclusions("hibernate-validator-*.jar") +class ModifiedClassPathExtensionExclusionsTests { + + private static final String EXCLUDED_RESOURCE = "META-INF/services/" + "javax.validation.spi.ValidationProvider"; + + @Test + void entriesAreFilteredFromTestClassClassLoader() { + assertThat(getClass().getClassLoader().getResource(EXCLUDED_RESOURCE)).isNull(); + } + + @Test + void entriesAreFilteredFromThreadContextClassLoader() { + assertThat(Thread.currentThread().getContextClassLoader().getResource(EXCLUDED_RESOURCE)).isNull(); + } + + @Test + void testsThatUseHamcrestWorkCorrectly() { + Matcher matcher = isA(IllegalStateException.class); + assertThat(matcher.matches(new IllegalStateException())).isTrue(); + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java new file mode 100644 index 000000000000..59a8b8fb6c16 --- /dev/null +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java @@ -0,0 +1,48 @@ +/* + * 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.testsupport.runner.classpath; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.context.ApplicationContext; +import org.springframework.util.StringUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for {@link ModifiedClassPathExtension} overriding entries on the class path. + * + * @author Andy Wilkinson + */ +@ExtendWith(ModifiedClassPathExtension.class) +@ClassPathOverrides("org.springframework:spring-context:4.1.0.RELEASE") +class ModifiedClassPathExtensionOverridesTests { + + @Test + void classesAreLoadedFromOverride() { + assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) + .endsWith("spring-context-4.1.0.RELEASE.jar"); + } + + @Test + void classesAreLoadedFromTransitiveDependencyOfOverride() { + assertThat(StringUtils.class.getProtectionDomain().getCodeSource().getLocation().toString()) + .endsWith("spring-core-4.1.0.RELEASE.jar"); + } + +} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java index a96e4cfb2689..8c9f3ae536eb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java @@ -28,6 +28,7 @@ * * @author Andy Wilkinson */ +@SuppressWarnings("deprecation") @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions("hibernate-validator-*.jar") public class ModifiedClassPathRunnerExclusionsTests { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java index 557bfd1bfa6d..55e6402a93d8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerOverridesTests.java @@ -29,6 +29,7 @@ * * @author Andy Wilkinson */ +@SuppressWarnings("deprecation") @RunWith(ModifiedClassPathRunner.class) @ClassPathOverrides("org.springframework:spring-context:4.1.0.RELEASE") public class ModifiedClassPathRunnerOverridesTests { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java index fb5cbf075c3e..7d6299b3dd24 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java @@ -16,12 +16,11 @@ package org.springframework.boot; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.StaticApplicationContext; @@ -33,31 +32,23 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("spring-web*.jar") -public class SpringApplicationNoWebTests { - - private ConfigurableApplicationContext context; - - @After - public void cleanUp() { - if (this.context != null) { - this.context.close(); - } - } +class SpringApplicationNoWebTests { @Test - public void detectWebApplicationTypeToNone() { + void detectWebApplicationTypeToNone() { SpringApplication application = new SpringApplication(ExampleConfig.class); assertThat(application.getWebApplicationType()).isEqualTo(WebApplicationType.NONE); } @Test - public void specificApplicationContextClass() { + void specificApplicationContextClass() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(StaticApplicationContext.class); - this.context = application.run(); - assertThat(this.context).isInstanceOf(StaticApplicationContext.class); + ConfigurableApplicationContext context = application.run(); + assertThat(context).isInstanceOf(StaticApplicationContext.class); + context.close(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java index 8a5ea5e194b9..0140a48863bf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java @@ -18,6 +18,8 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -32,12 +34,10 @@ import ch.qos.logback.classic.LoggerContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.bridge.SLF4JBridgeHandler; import org.slf4j.impl.StaticLoggerBinder; @@ -56,8 +56,9 @@ import org.springframework.boot.logging.java.JavaLoggingSystem; import org.springframework.boot.system.ApplicationPid; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; -import org.springframework.boot.testsupport.system.OutputCaptureRule; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; @@ -68,12 +69,11 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.util.FileSystemUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; /** * Tests for {@link LoggingApplicationListener} with Logback. @@ -85,18 +85,13 @@ * @author Ben Hale * @author Fahim Farook */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) +@ExtendWith(OutputCaptureExtension.class) @ClassPathExclusions("log4j*.jar") -public class LoggingApplicationListenerTests { +class LoggingApplicationListenerTests { private static final String[] NO_ARGS = {}; - @Rule - public OutputCaptureRule outputCapture = new OutputCaptureRule(); - - @Rule - public final TemporaryFolder temp = new TemporaryFolder(); - private final LoggingApplicationListener initializer = new LoggingApplicationListener(); private final LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory(); @@ -107,23 +102,33 @@ public class LoggingApplicationListenerTests { private final GenericApplicationContext context = new GenericApplicationContext(); + private Path tempDir; + private File logFile; - @Before - public void init() throws SecurityException, IOException { + private CapturedOutput capturedOutput; + + @BeforeEach + void init(CapturedOutput capturedOutput) throws SecurityException, IOException { + this.capturedOutput = capturedOutput; + this.tempDir = Files.createTempDirectory("logging-application-listener-tests"); + this.logFile = new File(this.tempDir.toFile(), "foo.log"); LogManager.getLogManager().readConfiguration(JavaLoggingSystem.class.getResourceAsStream("logging.properties")); multicastEvent(new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); - this.logFile = new File(this.temp.getRoot(), "foo.log"); - new File(tmpDir() + "/spring.log").delete(); + new File(this.tempDir.toFile(), "spring.log").delete(); ConfigurableEnvironment environment = this.context.getEnvironment(); ConfigurationPropertySources.attach(environment); } - @After - public void clear() { + @AfterEach + void clear() throws IOException { LoggingSystem loggingSystem = LoggingSystem.get(getClass().getClassLoader()); loggingSystem.setLogLevel("ROOT", LogLevel.INFO); loggingSystem.cleanUp(); + if (loggingSystem.getShutdownHandler() != null) { + loggingSystem.getShutdownHandler().run(); + } + FileSystemUtils.deleteRecursively(this.tempDir); System.clearProperty(LoggingSystem.class.getName()); System.clearProperty(LoggingSystemProperties.LOG_FILE); System.clearProperty(LoggingSystemProperties.LOG_PATH); @@ -138,103 +143,92 @@ public void clear() { } } - private String tmpDir() { - String path = this.context.getEnvironment().resolvePlaceholders("${java.io.tmpdir}"); - path = path.replace("\\", "/"); - if (path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - return path; - } - @Test - public void baseConfigLocation() { + void baseConfigLocation() { this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); - this.outputCapture.expect(containsString("Hello world")); - this.outputCapture.expect(not(containsString("???"))); - this.outputCapture.expect(containsString("[junit-")); this.logger.info("Hello world", new RuntimeException("Expected")); - assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); + assertThat(this.capturedOutput).contains("Hello world"); + assertThat(this.capturedOutput).doesNotContain("???"); + assertThat(this.capturedOutput).contains("[junit-"); + assertThat(new File(this.tempDir + "/spring.log").exists()).isFalse(); } @Test - public void overrideConfigLocation() { + void overrideConfigLocation() { addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); - String output = this.outputCapture.toString().trim(); - assertThat(output).contains("Hello world").doesNotContain("???").startsWith("null ").endsWith("BOOTBOOT"); + assertThat(this.capturedOutput).contains("Hello world").doesNotContain("???").startsWith("null ") + .endsWith("BOOTBOOT"); } @Test - public void overrideConfigDoesNotExist() { + void overrideConfigDoesNotExist() { addPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); assertThatIllegalStateException().isThrownBy(() -> { - this.outputCapture.expect( - containsString("Logging system failed to initialize using configuration from 'doesnotexist.xml'")); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); + assertThat(this.capturedOutput) + .contains("Logging system failed to initialize using configuration from 'doesnotexist.xml'"); }); } @Test - public void azureDefaultLoggingConfigDoesNotCauseAFailure() { + void azureDefaultLoggingConfigDoesNotCauseAFailure() { addPropertiesToEnvironment(this.context, "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.logger.info("Hello world"); - String output = this.outputCapture.toString().trim(); - assertThat(output).contains("Hello world").doesNotContain("???"); - assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); + assertThat(this.capturedOutput).contains("Hello world").doesNotContain("???"); + assertThat(new File(this.tempDir.toFile(), "/spring.log").exists()).isFalse(); } @Test - public void tomcatNopLoggingConfigDoesNotCauseAFailure() { + void tomcatNopLoggingConfigDoesNotCauseAFailure() { addPropertiesToEnvironment(this.context, "LOGGING_CONFIG=-Dnop"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.info("Hello world"); - String output = this.outputCapture.toString().trim(); - assertThat(output).contains("Hello world").doesNotContain("???"); - assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); + assertThat(this.capturedOutput).contains("Hello world").doesNotContain("???"); + assertThat(new File(this.tempDir.toFile(), "/spring.log").exists()).isFalse(); } @Test - public void overrideConfigBroken() { + void overrideConfigBroken() { addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-broken.xml"); assertThatIllegalStateException().isThrownBy(() -> { - this.outputCapture.expect(containsString( - "Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'")); - this.outputCapture.expect(containsString("ConsolAppender")); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); + assertThat(this.capturedOutput).contains( + "Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'"); + assertThat(this.capturedOutput).contains("ConsolAppender"); }); } @Test - public void addLogFileProperty() { + void addLogFileProperty() { addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", "logging.file.name=" + this.logFile); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); - String existingOutput = this.outputCapture.toString(); + String existingOutput = this.capturedOutput.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); + String output = this.capturedOutput.toString().substring(existingOutput.length()).trim(); assertThat(output).startsWith(this.logFile.getAbsolutePath()); } @Test @Deprecated - public void addLogFilePropertyWithDeprecatedProperty() { + void addLogFilePropertyWithDeprecatedProperty() { addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", "logging.file=" + this.logFile); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); - String existingOutput = this.outputCapture.toString(); + String existingOutput = this.capturedOutput.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); + String output = this.capturedOutput.toString().substring(existingOutput.length()).trim(); assertThat(output).startsWith(this.logFile.getAbsolutePath()); } @Test - public void addLogFilePropertyWithDefault() { + void addLogFilePropertyWithDefault() { assertThat(this.logFile).doesNotExist(); addPropertiesToEnvironment(this.context, "logging.file.name=" + this.logFile); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); @@ -245,8 +239,7 @@ public void addLogFilePropertyWithDefault() { @Test @Deprecated - public void addLogFilePropertyWithDefaultAndDeprecatedProperty() { - assertThat(this.logFile).doesNotExist(); + void addLogFilePropertyWithDefaultAndDeprecatedProperty() { addPropertiesToEnvironment(this.context, "logging.file=" + this.logFile); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); @@ -255,66 +248,66 @@ public void addLogFilePropertyWithDefaultAndDeprecatedProperty() { } @Test - public void addLogPathProperty() { + void addLogPathProperty() { addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", - "logging.file.path=" + this.temp.getRoot()); + "logging.file.path=" + this.tempDir); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); - String existingOutput = this.outputCapture.toString(); + String existingOutput = this.capturedOutput.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); - assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); + String output = this.capturedOutput.toString().substring(existingOutput.length()).trim(); + assertThat(output).startsWith(new File(this.tempDir.toFile(), "spring.log").getAbsolutePath()); } @Test - public void addLogPathPropertyWithDeprecatedProperty() { + void addLogPathPropertyWithDeprecatedProperty() { addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", - "logging.path=" + this.temp.getRoot()); + "logging.path=" + this.tempDir); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); - String existingOutput = this.outputCapture.toString(); + String existingOutput = this.capturedOutput.toString(); logger.info("Hello world"); - String output = this.outputCapture.toString().substring(existingOutput.length()).trim(); - assertThat(output).startsWith(new File(this.temp.getRoot(), "spring.log").getAbsolutePath()); + String output = this.capturedOutput.toString().substring(existingOutput.length()).trim(); + assertThat(output).startsWith(new File(this.tempDir.toFile(), "spring.log").getAbsolutePath()); } @Test - public void parseDebugArg() { + void parseDebugArg() { addPropertiesToEnvironment(this.context, "debug"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString()).contains("testatdebug"); - assertThat(this.outputCapture.toString()).doesNotContain("testattrace"); + assertThat(this.capturedOutput).contains("testatdebug"); + assertThat(this.capturedOutput).doesNotContain("testattrace"); } @Test - public void parseDebugArgExpandGroups() { + void parseDebugArgExpandGroups() { addPropertiesToEnvironment(this.context, "debug"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.loggerContext.getLogger("org.springframework.boot.actuate.endpoint.web").debug("testdebugwebgroup"); this.loggerContext.getLogger("org.hibernate.SQL").debug("testdebugsqlgroup"); - assertThat(this.outputCapture.toString()).contains("testdebugwebgroup"); - assertThat(this.outputCapture.toString()).contains("testdebugsqlgroup"); + assertThat(this.capturedOutput).contains("testdebugwebgroup"); + assertThat(this.capturedOutput).contains("testdebugsqlgroup"); } @Test - public void parseTraceArg() { + void parseTraceArg() { addPropertiesToEnvironment(this.context, "trace"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString()).contains("testatdebug"); - assertThat(this.outputCapture.toString()).contains("testattrace"); + assertThat(this.capturedOutput).contains("testatdebug"); + assertThat(this.capturedOutput).contains("testattrace"); } @Test - public void disableDebugArg() { + void disableDebugArg() { disableDebugTraceArg("debug=false"); } @Test - public void disableTraceArg() { + void disableTraceArg() { disableDebugTraceArg("trace=false"); } @@ -323,52 +316,52 @@ private void disableDebugTraceArg(String... environment) { this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); - assertThat(this.outputCapture.toString()).doesNotContain("testattrace"); + assertThat(this.capturedOutput).doesNotContain("testatdebug"); + assertThat(this.capturedOutput).doesNotContain("testattrace"); } @Test - public void parseLevels() { + void parseLevels() { addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=TRACE"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString()).contains("testatdebug"); - assertThat(this.outputCapture.toString()).contains("testattrace"); + assertThat(this.capturedOutput).contains("testatdebug"); + assertThat(this.capturedOutput).contains("testattrace"); } @Test - public void parseLevelsCaseInsensitive() { + void parseLevelsCaseInsensitive() { addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=TrAcE"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString()).contains("testatdebug"); - assertThat(this.outputCapture.toString()).contains("testattrace"); + assertThat(this.capturedOutput).contains("testatdebug"); + assertThat(this.capturedOutput).contains("testattrace"); } @Test - public void parseLevelsTrimsWhitespace() { + void parseLevelsTrimsWhitespace() { addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot= trace "); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString()).contains("testatdebug"); - assertThat(this.outputCapture.toString()).contains("testattrace"); + assertThat(this.capturedOutput).contains("testatdebug"); + assertThat(this.capturedOutput).contains("testattrace"); } @Test - public void parseLevelsWithPlaceholder() { + void parseLevelsWithPlaceholder() { addPropertiesToEnvironment(this.context, "foo=TRACE", "logging.level.org.springframework.boot=${foo}"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString()).contains("testatdebug"); - assertThat(this.outputCapture.toString()).contains("testattrace"); + assertThat(this.capturedOutput).contains("testatdebug"); + assertThat(this.capturedOutput).contains("testattrace"); } @Test - public void parseLevelsFails() { + void parseLevelsFails() { this.logger.setLevel(Level.INFO); addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=GARBAGE"); assertThatExceptionOfType(BindException.class).isThrownBy( @@ -376,68 +369,68 @@ public void parseLevelsFails() { } @Test - public void parseLevelsNone() { + void parseLevelsNone() { addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=OFF"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.error("testaterror"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testaterror"); + assertThat(this.capturedOutput).doesNotContain("testatdebug").doesNotContain("testaterror"); } @Test - public void parseLevelsMapsFalseToOff() { + void parseLevelsMapsFalseToOff() { addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=false"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.error("testaterror"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testaterror"); + assertThat(this.capturedOutput).doesNotContain("testatdebug").doesNotContain("testaterror"); } @Test - public void parseArgsDisabled() { + void parseArgsDisabled() { this.initializer.setParseArgs(false); addPropertiesToEnvironment(this.context, "debug"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); + assertThat(this.capturedOutput).doesNotContain("testatdebug"); } @Test - public void parseArgsDoesntReplace() { + void parseArgsDoesntReplace() { this.initializer.setSpringBootLogging(LogLevel.ERROR); this.initializer.setParseArgs(false); multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[] { "--debug" })); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); + assertThat(this.capturedOutput).doesNotContain("testatdebug"); } @Test - public void bridgeHandlerLifecycle() { + void bridgeHandlerLifecycle() { assertThat(bridgeHandlerInstalled()).isTrue(); multicastEvent(new ContextClosedEvent(this.context)); assertThat(bridgeHandlerInstalled()).isFalse(); } @Test - public void defaultExceptionConversionWord() { + void defaultExceptionConversionWord() { this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); - this.outputCapture.expect(containsString("Hello world")); - this.outputCapture.expect(not(containsString("Wrapped by: java.lang.RuntimeException: Wrapper"))); this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); + assertThat(this.capturedOutput).contains("Hello world"); + assertThat(this.capturedOutput).doesNotContain("Wrapped by: java.lang.RuntimeException: Wrapper"); } @Test - public void overrideExceptionConversionWord() { + void overrideExceptionConversionWord() { addPropertiesToEnvironment(this.context, "logging.exceptionConversionWord=%rEx"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); - this.outputCapture.expect(containsString("Hello world")); - this.outputCapture.expect(containsString("Wrapped by: java.lang.RuntimeException: Wrapper")); this.logger.info("Hello world", new RuntimeException("Wrapper", new RuntimeException("Expected"))); + assertThat(this.capturedOutput).contains("Hello world"); + assertThat(this.capturedOutput).contains("Wrapped by: java.lang.RuntimeException: Wrapper"); } @Test - public void shutdownHookIsNotRegisteredByDefault() { + void shutdownHookIsNotRegisteredByDefault() { TestLoggingApplicationListener listener = new TestLoggingApplicationListener(); System.setProperty(LoggingSystem.class.getName(), TestShutdownHandlerLoggingSystem.class.getName()); multicastEvent(listener, new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); @@ -446,7 +439,7 @@ public void shutdownHookIsNotRegisteredByDefault() { } @Test - public void shutdownHookCanBeRegistered() throws Exception { + void shutdownHookCanBeRegistered() throws Exception { TestLoggingApplicationListener listener = new TestLoggingApplicationListener(); System.setProperty(LoggingSystem.class.getName(), TestShutdownHandlerLoggingSystem.class.getName()); addPropertiesToEnvironment(this.context, "logging.register_shutdown_hook=true"); @@ -458,7 +451,7 @@ public void shutdownHookCanBeRegistered() throws Exception { } @Test - public void closingContextCleansUpLoggingSystem() { + void closingContextCleansUpLoggingSystem() { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils @@ -469,7 +462,7 @@ public void closingContextCleansUpLoggingSystem() { } @Test - public void closingChildContextDoesNotCleanUpLoggingSystem() { + void closingChildContextDoesNotCleanUpLoggingSystem() { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils @@ -485,7 +478,7 @@ public void closingChildContextDoesNotCleanUpLoggingSystem() { } @Test - public void systemPropertiesAreSetForLoggingConfiguration() { + void systemPropertiesAreSetForLoggingConfiguration() { addPropertiesToEnvironment(this.context, "logging.exception-conversion-word=conversion", "logging.file.name=" + this.logFile, "logging.file.path=path", "logging.pattern.console=console", "logging.pattern.file=file", "logging.pattern.level=level"); @@ -501,7 +494,7 @@ public void systemPropertiesAreSetForLoggingConfiguration() { @Test @Deprecated - public void systemPropertiesAreSetForLoggingConfigurationWithDeprecatedProperties() { + void systemPropertiesAreSetForLoggingConfigurationWithDeprecatedProperties() { addPropertiesToEnvironment(this.context, "logging.file=" + this.logFile, "logging.path=path"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)).isEqualTo(this.logFile.getAbsolutePath()); @@ -509,7 +502,7 @@ public void systemPropertiesAreSetForLoggingConfigurationWithDeprecatedPropertie } @Test - public void environmentPropertiesIgnoreUnresolvablePlaceholders() { + void environmentPropertiesIgnoreUnresolvablePlaceholders() { // gh-7719 addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${doesnotexist}"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); @@ -518,7 +511,7 @@ public void environmentPropertiesIgnoreUnresolvablePlaceholders() { } @Test - public void environmentPropertiesResolvePlaceholders() { + void environmentPropertiesResolvePlaceholders() { addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${pid}"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) @@ -526,16 +519,15 @@ public void environmentPropertiesResolvePlaceholders() { } @Test - public void logFilePropertiesCanReferenceSystemProperties() { - addPropertiesToEnvironment(this.context, - "logging.file.name=" + this.temp.getRoot().getAbsolutePath() + "${PID}.log"); + void logFilePropertiesCanReferenceSystemProperties() { + addPropertiesToEnvironment(this.context, "logging.file.name=" + this.tempDir + "${PID}.log"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo(this.temp.getRoot().getAbsolutePath() + new ApplicationPid().toString() + ".log"); + .isEqualTo(this.tempDir + new ApplicationPid().toString() + ".log"); } @Test - public void applicationFailedEventCleansUpLoggingSystem() { + void applicationFailedEventCleansUpLoggingSystem() { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils @@ -547,18 +539,18 @@ public void applicationFailedEventCleansUpLoggingSystem() { } @Test - public void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() { + void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() { MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources(); propertySources .addFirst(new MapPropertySource("test1", Collections.singletonMap("logging.level.ROOT", "DEBUG"))); propertySources.addLast(new MapPropertySource("test2", Collections.singletonMap("logging.level.root", "WARN"))); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString()).contains("testatdebug"); + assertThat(this.capturedOutput).contains("testatdebug"); } @Test - public void loggingGroupsDefaultsAreApplied() { + void loggingGroupsDefaultsAreApplied() { addPropertiesToEnvironment(this.context, "logging.level.web=TRACE"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertTraceEnabled("org.springframework.core", false); @@ -570,7 +562,7 @@ public void loggingGroupsDefaultsAreApplied() { } @Test - public void loggingGroupsCanBeDefined() { + void loggingGroupsCanBeDefined() { addPropertiesToEnvironment(this.context, "logging.group.foo=com.foo.bar,com.foo.baz", "logging.level.foo=TRACE"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); @@ -670,11 +662,11 @@ void registerShutdownHook(Thread shutdownHook) { } - public static final class TestCleanupLoggingSystem extends LoggingSystem { + static final class TestCleanupLoggingSystem extends LoggingSystem { private boolean cleanedUp = false; - public TestCleanupLoggingSystem(ClassLoader classLoader) { + TestCleanupLoggingSystem(ClassLoader classLoader) { } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java index 2e80d8953d0d..a069085b62be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java @@ -19,12 +19,12 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.testsupport.runner.classpath.ClassPathOverrides; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -34,12 +34,12 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathOverrides("javax.servlet:servlet-api:2.5") -public class NoSuchMethodFailureAnalyzerTests { +class NoSuchMethodFailureAnalyzerTests { @Test - public void noSuchMethodErrorIsAnalyzed() { + void noSuchMethodErrorIsAnalyzed() { Throwable failure = createFailure(); assertThat(failure).isNotNull(); FailureAnalysis analysis = new NoSuchMethodFailureAnalyzer().analyze(failure); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java index 1f922891586a..9c355b50af68 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java @@ -16,13 +16,13 @@ package org.springframework.boot.diagnostics.analyzer; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.validation.annotation.Validated; @@ -34,19 +34,19 @@ * * @author Andy Wilkinson */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("hibernate-validator-*.jar") -public class ValidationExceptionFailureAnalyzerTests { +class ValidationExceptionFailureAnalyzerTests { @Test - public void validatedPropertiesTest() { + void validatedPropertiesTest() { assertThatExceptionOfType(Exception.class) .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); } @Test - public void nonValidatedPropertiesTest() { + void nonValidatedPropertiesTest() { new AnnotationConfigApplicationContext(NonValidatedTestConfiguration.class).close(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java index 71de086c23c6..7f03b0769a44 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java @@ -16,11 +16,11 @@ package org.springframework.boot.env; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.core.io.ByteArrayResource; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @@ -30,14 +30,14 @@ * * @author Madhura Bhave */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("snakeyaml-*.jar") -public class NoSnakeYamlPropertySourceLoaderTests { +class NoSnakeYamlPropertySourceLoaderTests { private YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Test - public void load() throws Exception { + void load() throws Exception { ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); assertThatIllegalStateException().isThrownBy(() -> this.loader.load("resource", resource)) .withMessageContaining("Attempted to load resource but snakeyaml was not found on the classpath"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java index 768b864cdfca..c8776d1a7be0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java @@ -20,12 +20,12 @@ import com.zaxxer.hikari.HikariDataSource; import org.apache.tomcat.jdbc.pool.DataSourceProxy; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.aop.framework.ProxyFactory; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import static org.assertj.core.api.Assertions.assertThat; @@ -34,19 +34,19 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("spring-jdbc-*.jar") -public class DataSourceUnwrapperNoSpringJdbcTests { +class DataSourceUnwrapperNoSpringJdbcTests { @Test - public void unwrapWithProxy() { + void unwrapWithProxy() { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariDataSource.class)).isSameAs(dataSource); } @Test - public void unwrapDataSourceProxy() { + void unwrapDataSourceProxy() { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, DataSourceProxy.class)).isSameAs(dataSource); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java index 41936b88f71f..723aaaf17e57 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java @@ -21,11 +21,11 @@ import javax.validation.ValidationException; import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -35,12 +35,12 @@ * * @author Phillip Webb */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("tomcat-embed-el-*.jar") -public class MessageInterpolatorFactoryWithoutElIntegrationTests { +class MessageInterpolatorFactoryWithoutElIntegrationTests { @Test - public void defaultMessageInterpolatorShouldFail() { + void defaultMessageInterpolatorShouldFail() { // Sanity test assertThatExceptionOfType(ValidationException.class) .isThrownBy(Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) @@ -48,7 +48,7 @@ public void defaultMessageInterpolatorShouldFail() { } @Test - public void getObjectShouldUseFallback() { + void getObjectShouldUseFallback() { MessageInterpolator interpolator = new MessageInterpolatorFactory().getObject(); assertThat(interpolator).isInstanceOf(ParameterMessageInterpolator.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java index 5d799cbab59c..88ee749faa39 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java @@ -19,11 +19,11 @@ import java.time.Duration; import okhttp3.OkHttpClient; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; import org.springframework.test.util.ReflectionTestUtils; @@ -38,20 +38,20 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions("httpclient-*.jar") -public class HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests { +class HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests { private final HttpWebServiceMessageSenderBuilder builder = new HttpWebServiceMessageSenderBuilder(); @Test - public void buildUseOkHttp3ByDefault() { + void buildUseOkHttp3ByDefault() { WebServiceMessageSender messageSender = this.builder.build(); assertOkHttp3RequestFactory(messageSender); } @Test - public void buildWithCustomTimeouts() { + void buildWithCustomTimeouts() { WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(2)).build(); OkHttp3ClientHttpRequestFactory factory = assertOkHttp3RequestFactory(messageSender); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java index 0e61a0d200ef..bb806d6550de 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java @@ -18,11 +18,11 @@ import java.time.Duration; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; +import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathExtension; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.ws.transport.WebServiceMessageSender; @@ -36,20 +36,20 @@ * * @author Stephane Nicoll */ -@RunWith(ModifiedClassPathRunner.class) +@ExtendWith(ModifiedClassPathExtension.class) @ClassPathExclusions({ "httpclient-*.jar", "okhttp*.jar" }) -public class HttpWebServiceMessageSenderBuilderSimpleIntegrationTests { +class HttpWebServiceMessageSenderBuilderSimpleIntegrationTests { private final HttpWebServiceMessageSenderBuilder builder = new HttpWebServiceMessageSenderBuilder(); @Test - public void buildUseUseSimpleClientByDefault() { + void buildUseUseSimpleClientByDefault() { WebServiceMessageSender messageSender = this.builder.build(); assertSimpleClientRequestFactory(messageSender); } @Test - public void buildWithCustomTimeouts() { + void buildWithCustomTimeouts() { WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(2)).build(); SimpleClientHttpRequestFactory requestFactory = assertSimpleClientRequestFactory(messageSender); diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml index 0db457a40894..66c81d62e744 100644 --- a/src/checkstyle/checkstyle-suppressions.xml +++ b/src/checkstyle/checkstyle-suppressions.xml @@ -41,7 +41,6 @@ - diff --git a/src/checkstyle/checkstyle.xml b/src/checkstyle/checkstyle.xml index 312d27601d73..65fad54150a6 100644 --- a/src/checkstyle/checkstyle.xml +++ b/src/checkstyle/checkstyle.xml @@ -8,9 +8,7 @@ - - - + From 88c37504424182e6bfd91421219ba951f4c0bf8a Mon Sep 17 00:00:00 2001 From: dreis2211 Date: Fri, 12 Jul 2019 00:25:30 +0200 Subject: [PATCH 2/2] Avoid executing tests twice in ModifiedClassPathExtension --- .../classpath/ModifiedClassPathExtension.java | 47 ++++++++++++++++--- ...ifiedClassPathExtensionOverridesTests.java | 2 +- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java index 8e661a6ed932..88c1b5364078 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtension.java @@ -16,8 +16,10 @@ package org.springframework.boot.testsupport.runner.classpath; +import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URLClassLoader; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.ExtensionContext; @@ -42,15 +44,35 @@ * class loader is created with the customized class path and is used both to load the * test class and as the thread context class loader while the test is being run. * - * NOTE: As JUnit 5 doesn't support native class loader support yet, this extension - * executes the tests with the modified class loader via the {@link Launcher} facilities. - * While the original test results are swallowed, the test itself is still executed. - * * @author Christoph Dreis * @since 2.2.0 */ public class ModifiedClassPathExtension implements InvocationInterceptor { + @Override + public void interceptBeforeAllMethod(Invocation invocation, + ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) throws Throwable { + interceptInvocation(invocation, extensionContext); + } + + @Override + public void interceptBeforeEachMethod(Invocation invocation, + ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) throws Throwable { + interceptInvocation(invocation, extensionContext); + } + + @Override + public void interceptAfterEachMethod(Invocation invocation, + ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) throws Throwable { + interceptInvocation(invocation, extensionContext); + } + + @Override + public void interceptAfterAllMethod(Invocation invocation, + ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) throws Throwable { + interceptInvocation(invocation, extensionContext); + } + @Override public void interceptTestMethod(Invocation invocation, ReflectiveInvocationContext invocationContext, ExtensionContext extensionContext) throws Throwable { @@ -63,7 +85,7 @@ public void interceptTestMethod(Invocation invocation, ReflectiveInvocatio .createTestClassLoader(extensionContext.getRequiredTestClass()); Thread.currentThread().setContextClassLoader(classLoader); try { - swallowOriginalInvocation(invocation); + fakeInvocation(invocation); TestExecutionSummary summary = launchTests(invocationContext, extensionContext, classLoader); if (!CollectionUtils.isEmpty(summary.getFailures())) { throw summary.getFailures().get(0).getException(); @@ -96,10 +118,21 @@ private boolean isModifiedClassPathClassLoader(ExtensionContext extensionContext .equals(ModifiedClassPathClassLoader.class.getName()); } - private void swallowOriginalInvocation(Invocation invocation) { - try { + private void interceptInvocation(Invocation invocation, ExtensionContext extensionContext) throws Throwable { + if (isModifiedClassPathClassLoader(extensionContext)) { invocation.proceed(); } + else { + fakeInvocation(invocation); + } + } + + private void fakeInvocation(Invocation invocation) { + try { + Field field = ReflectionUtils.findField(invocation.getClass(), "invoked"); + ReflectionUtils.makeAccessible(field); + ReflectionUtils.setField(field, invocation, new AtomicBoolean(true)); + } catch (Throwable ignore) { } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java index 59a8b8fb6c16..0dda8cca68ae 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathExtensionOverridesTests.java @@ -27,7 +27,7 @@ /** * Tests for {@link ModifiedClassPathExtension} overriding entries on the class path. * - * @author Andy Wilkinson + * @author Christoph Dreis */ @ExtendWith(ModifiedClassPathExtension.class) @ClassPathOverrides("org.springframework:spring-context:4.1.0.RELEASE")