diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java index b7573c4f177..f8db8df9a27 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java @@ -21,6 +21,7 @@ import java.util.Map; import javax.sql.DataSource; import io.searchbox.client.JestClient; +import org.assertj.core.api.Condition; import org.junit.Test; import org.neo4j.ogm.session.SessionFactory; @@ -42,11 +43,14 @@ import org.springframework.boot.actuate.health.Neo4jHealthIndicator; import org.springframework.boot.actuate.health.RabbitHealthIndicator; import org.springframework.boot.actuate.health.RedisHealthIndicator; import org.springframework.boot.actuate.health.SolrHealthIndicator; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration; import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration; import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration; import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration; @@ -56,8 +60,9 @@ import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.ApplicationContextTester; +import org.springframework.boot.test.context.AssertableApplicationContext; import org.springframework.boot.test.context.ContextConsumer; -import org.springframework.boot.test.context.ContextLoader; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.core.CassandraOperations; @@ -79,81 +84,86 @@ import static org.mockito.Mockito.mock; */ public class HealthIndicatorAutoConfigurationTests { - public final ContextLoader contextLoader = ContextLoader.standard().autoConfig( - HealthIndicatorAutoConfiguration.class, ManagementServerProperties.class); + public final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration( + AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, + ManagementServerProperties.class)); @Test public void defaultHealthIndicator() { - this.contextLoader.env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + this.context.withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void defaultHealthIndicatorsDisabled() { - this.contextLoader.env("management.health.defaults.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + this.context.withPropertyValues("management.health.defaults.enabled:false") + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void defaultHealthIndicatorsDisabledWithCustomOne() { - this.contextLoader.config(CustomHealthIndicator.class) - .env("management.health.defaults.enabled:false").load(context -> { - Map beans = context + this.context.withUserConfiguration(CustomHealthIndicator.class) + .withPropertyValues("management.health.defaults.enabled:false") + .run((loaded) -> { + Map beans = loaded .getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); - assertThat(context.getBean("customHealthIndicator")) + assertThat(loaded.getBean("customHealthIndicator")) .isSameAs(beans.values().iterator().next()); }); } @Test public void defaultHealthIndicatorsDisabledButOne() { - this.contextLoader - .env("management.health.defaults.enabled:false", + this.context + .withPropertyValues("management.health.defaults.enabled:false", "management.health.diskspace.enabled:true") - .load(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class)); + .run(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class)); } @Test public void redisHealthIndicator() { - this.contextLoader.autoConfigFirst(RedisAutoConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(RedisHealthIndicator.class)); + this.context + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(RedisHealthIndicator.class)); } @Test public void notRedisHealthIndicator() { - this.contextLoader.autoConfigFirst(RedisAutoConfiguration.class) - .env("management.health.redis.enabled:false", + this.context + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .withPropertyValues("management.health.redis.enabled:false", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void mongoHealthIndicator() { - this.contextLoader - .autoConfigFirst(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(MongoHealthIndicator.class)); + this.context + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(MongoHealthIndicator.class)); } @Test public void notMongoHealthIndicator() { - this.contextLoader - .autoConfigFirst(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class) - .env("management.health.mongo.enabled:false", + this.context + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class)) + .withPropertyValues("management.health.mongo.enabled:false", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void combinedHealthIndicator() { - this.contextLoader.autoConfigFirst(MongoAutoConfiguration.class, + this.context.withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, RedisAutoConfiguration.class, MongoDataAutoConfiguration.class, - SolrAutoConfiguration.class).load(context -> { - Map beans = context + SolrAutoConfiguration.class)).run((loaded) -> { + Map beans = loaded .getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(4); }); @@ -161,17 +171,21 @@ public class HealthIndicatorAutoConfigurationTests { @Test public void dataSourceHealthIndicator() { - this.contextLoader.autoConfigFirst(EmbeddedDataSourceConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(DataSourceHealthIndicator.class)); + this.context + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(DataSourceHealthIndicator.class)); } @Test public void dataSourceHealthIndicatorWithSeveralDataSources() { - this.contextLoader - .config(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class) - .env("management.health.diskspace.enabled:false").load(context -> { - Map beans = context + this.context + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, + DataSourceConfig.class) + .withPropertyValues("management.health.diskspace.enabled:false") + .run((loaded) -> { + Map beans = loaded .getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); HealthIndicator bean = beans.values().iterator().next(); @@ -183,23 +197,24 @@ public class HealthIndicatorAutoConfigurationTests { @Test public void dataSourceHealthIndicatorWithAbstractRoutingDataSource() { - this.contextLoader - .config(EmbeddedDataSourceConfiguration.class, + this.context + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDatasourceConfig.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(DataSourceHealthIndicator.class)); + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(DataSourceHealthIndicator.class)); } @Test public void dataSourceHealthIndicatorWithCustomValidationQuery() { - this.contextLoader - .config(DataSourceConfig.class, + this.context + .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class, HealthIndicatorAutoConfiguration.class) - .env("spring.datasource.test.validation-query:SELECT from FOOBAR", + .withPropertyValues( + "spring.datasource.test.validation-query:SELECT from FOOBAR", "management.health.diskspace.enabled:false") - .load(context -> { - Map beans = context + .run((loaded) -> { + Map beans = loaded .getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); HealthIndicator healthIndicator = beans.values().iterator().next(); @@ -213,178 +228,192 @@ public class HealthIndicatorAutoConfigurationTests { @Test public void notDataSourceHealthIndicator() { - this.contextLoader.config(EmbeddedDataSourceConfiguration.class) - .env("management.health.db.enabled:false", + this.context.withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withPropertyValues("management.health.db.enabled:false", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void rabbitHealthIndicator() { - this.contextLoader.autoConfigFirst(RabbitAutoConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(RabbitHealthIndicator.class)); + this.context + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(RabbitHealthIndicator.class)); } @Test public void notRabbitHealthIndicator() { - this.contextLoader.autoConfigFirst(RabbitAutoConfiguration.class) - .env("management.health.rabbit.enabled:false", + this.context + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)) + .withPropertyValues("management.health.rabbit.enabled:false", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void solrHealthIndicator() { - this.contextLoader.autoConfigFirst(SolrAutoConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(SolrHealthIndicator.class)); + this.context.withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(SolrHealthIndicator.class)); } @Test public void notSolrHealthIndicator() { - this.contextLoader.autoConfigFirst(SolrAutoConfiguration.class) - .env("management.health.solr.enabled:false", + this.context.withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class)) + .withPropertyValues("management.health.solr.enabled:false", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void diskSpaceHealthIndicator() { - this.contextLoader.load(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class)); + this.context.run(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class)); } @Test public void mailHealthIndicator() { - this.contextLoader.autoConfigFirst(MailSenderAutoConfiguration.class) - .env("spring.mail.host:smtp.acme.org", + this.context + .withConfiguration( + AutoConfigurations.of(MailSenderAutoConfiguration.class)) + .withPropertyValues("spring.mail.host:smtp.acme.org", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(MailHealthIndicator.class)); + .run(hasSingleHealthIndicator(MailHealthIndicator.class)); } @Test public void notMailHealthIndicator() { - this.contextLoader.autoConfigFirst(MailSenderAutoConfiguration.class) - .env("spring.mail.host:smtp.acme.org", + this.context + .withConfiguration( + AutoConfigurations.of(MailSenderAutoConfiguration.class)) + .withPropertyValues("spring.mail.host:smtp.acme.org", "management.health.mail.enabled:false", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void jmsHealthIndicator() { - this.contextLoader.autoConfigFirst(ActiveMQAutoConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(JmsHealthIndicator.class)); + this.context + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(JmsHealthIndicator.class)); } @Test public void notJmsHealthIndicator() { - this.contextLoader.autoConfigFirst(ActiveMQAutoConfiguration.class) - .env("management.health.jms.enabled:false", + this.context + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class)) + .withPropertyValues("management.health.jms.enabled:false", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void elasticsearchHealthIndicator() { - this.contextLoader - .autoConfigFirst(JestClientConfiguration.class, - JestAutoConfiguration.class, ElasticsearchAutoConfiguration.class) - .env("spring.data.elasticsearch.cluster-nodes:localhost:0", + this.context + .withConfiguration(AutoConfigurations.of(JestClientConfiguration.class, + JestAutoConfiguration.class, + ElasticsearchAutoConfiguration.class)) + .withPropertyValues("spring.data.elasticsearch.cluster-nodes:localhost:0", "management.health.diskspace.enabled:false") - .systemProperty("es.set.netty.runtime.available.processors", "false") - .load(hasSingleHealthIndicator(ElasticsearchHealthIndicator.class)); + .withSystemProperties("es.set.netty.runtime.available.processors=false") + .run(hasSingleHealthIndicator(ElasticsearchHealthIndicator.class)); } @Test public void elasticsearchJestHealthIndicator() { - this.contextLoader - .autoConfigFirst(JestClientConfiguration.class, - JestAutoConfiguration.class) - .env("management.health.diskspace.enabled:false") - .systemProperty("es.set.netty.runtime.available.processors", "false") - .load(hasSingleHealthIndicator(ElasticsearchJestHealthIndicator.class)); + this.context + .withConfiguration(AutoConfigurations.of(JestClientConfiguration.class, + JestAutoConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .withSystemProperties("es.set.netty.runtime.available.processors=false") + .run(hasSingleHealthIndicator(ElasticsearchJestHealthIndicator.class)); } @Test public void notElasticsearchHealthIndicator() { - this.contextLoader - .autoConfigFirst(JestClientConfiguration.class, - JestAutoConfiguration.class, ElasticsearchAutoConfiguration.class) - .env("management.health.elasticsearch.enabled:false", + this.context + .withConfiguration(AutoConfigurations.of(JestClientConfiguration.class, + JestAutoConfiguration.class, + ElasticsearchAutoConfiguration.class)) + .withPropertyValues("management.health.elasticsearch.enabled:false", "spring.data.elasticsearch.properties.path.home:target", "management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void cassandraHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(CassandraConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(CassandraHealthIndicator.class)); + this.context + .withConfiguration(AutoConfigurations.of(CassandraConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(CassandraHealthIndicator.class)); } @Test public void notCassandraHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(CassandraConfiguration.class) - .env("management.health.diskspace.enabled:false", + this.context + .withConfiguration(AutoConfigurations.of(CassandraConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false", "management.health.cassandra.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void couchbaseHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(CouchbaseConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(CouchbaseHealthIndicator.class)); + this.context + .withConfiguration(AutoConfigurations.of(CouchbaseConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(CouchbaseHealthIndicator.class)); } @Test public void notCouchbaseHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(CouchbaseConfiguration.class) - .env("management.health.diskspace.enabled:false", + this.context + .withConfiguration(AutoConfigurations.of(CouchbaseConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false", "management.health.couchbase.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void ldapHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(LdapConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(LdapHealthIndicator.class)); + this.context.withConfiguration(AutoConfigurations.of(LdapConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(LdapHealthIndicator.class)); } @Test public void notLdapHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(LdapConfiguration.class) - .env("management.health.diskspace.enabled:false", + this.context.withConfiguration(AutoConfigurations.of(LdapConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false", "management.health.ldap.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } @Test public void neo4jHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(Neo4jConfiguration.class) - .env("management.health.diskspace.enabled:false") - .load(hasSingleHealthIndicator(Neo4jHealthIndicator.class)); + this.context.withConfiguration(AutoConfigurations.of(Neo4jConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false") + .run(hasSingleHealthIndicator(Neo4jHealthIndicator.class)); } @Test public void notNeo4jHealthIndicator() throws Exception { - this.contextLoader.autoConfigFirst(Neo4jConfiguration.class) - .env("management.health.diskspace.enabled:false", + this.context.withConfiguration(AutoConfigurations.of(Neo4jConfiguration.class)) + .withPropertyValues("management.health.diskspace.enabled:false", "management.health.neo4j.enabled:false") - .load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); + .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); } - private ContextConsumer hasSingleHealthIndicator( + private ContextConsumer hasSingleHealthIndicator( Class type) { - return context -> { - Map beans = context - .getBeansOfType(HealthIndicator.class); - assertThat(beans).hasSize(1); - assertThat(beans.values().iterator().next().getClass()).isEqualTo(type); + return (loaded) -> { + assertThat(loaded).getBeans(HealthIndicator.class).hasSize(1) + .hasValueSatisfying(new Condition<>( + (indicator) -> indicator.getClass().equals(type), + "Wrong indicator type")); }; } @@ -429,6 +458,7 @@ public class HealthIndicatorAutoConfigurationTests { } @Configuration + @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) protected static class CassandraConfiguration { @Bean @@ -439,6 +469,7 @@ public class HealthIndicatorAutoConfigurationTests { } @Configuration + @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) protected static class CouchbaseConfiguration { @Bean @@ -448,6 +479,7 @@ public class HealthIndicatorAutoConfigurationTests { } + @Configuration protected static class JestClientConfiguration { @Bean @@ -458,6 +490,7 @@ public class HealthIndicatorAutoConfigurationTests { } @Configuration + @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) protected static class LdapConfiguration { @Bean @@ -468,6 +501,7 @@ public class HealthIndicatorAutoConfigurationTests { } @Configuration + @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) protected static class Neo4jConfiguration { @Bean diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index aa18a6fbb3b..40c172b24a7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -52,10 +52,12 @@ import org.junit.runner.RunWith; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.cache.support.MockCachingProvider; import org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.test.context.ApplicationContextTester; +import org.springframework.boot.test.context.AssertableApplicationContext; +import org.springframework.boot.test.context.ContextConsumer; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.cache.Cache; @@ -72,7 +74,6 @@ import org.springframework.cache.interceptor.CacheResolver; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.cache.support.NoOpCacheManager; import org.springframework.cache.support.SimpleCacheManager; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -101,85 +102,88 @@ public class CacheAutoConfigurationTests { @Rule public final ExpectedException thrown = ExpectedException.none(); - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(CacheAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); @Test public void noEnableCaching() { - this.contextLoader.config(EmptyConfiguration.class).load(context -> { - this.thrown.expect(NoSuchBeanDefinitionException.class); - context.getBean(CacheManager.class); + this.context.withUserConfiguration(EmptyConfiguration.class).run((loaded) -> { + assertThat(loaded).doesNotHaveBean(CacheManager.class); }); } @Test public void cacheManagerBackOff() { - this.contextLoader.config(CustomCacheManagerConfiguration.class).load(context -> { - ConcurrentMapCacheManager cacheManager = validateCacheManager(context, - ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); - }); + this.context.withUserConfiguration(CustomCacheManagerConfiguration.class) + .run((loaded) -> { + assertThat(getCacheManager(loaded, ConcurrentMapCacheManager.class) + .getCacheNames()).containsOnly("custom1"); + }); } @Test public void cacheManagerFromSupportBackOff() { - this.contextLoader.config(CustomCacheManagerFromSupportConfiguration.class) - .load(context -> { - ConcurrentMapCacheManager cacheManager = validateCacheManager(context, - ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); + this.context + .withUserConfiguration(CustomCacheManagerFromSupportConfiguration.class) + .run((loaded) -> { + assertThat(getCacheManager(loaded, ConcurrentMapCacheManager.class) + .getCacheNames()).containsOnly("custom1"); }); } @Test public void cacheResolverFromSupportBackOff() throws Exception { - this.contextLoader.config(CustomCacheResolverFromSupportConfiguration.class) - .load(context -> { - this.thrown.expect(NoSuchBeanDefinitionException.class); - context.getBean(CacheManager.class); + this.context + .withUserConfiguration(CustomCacheResolverFromSupportConfiguration.class) + .run((loaded) -> { + assertThat(loaded).doesNotHaveBean(CacheManager.class); }); } @Test public void customCacheResolverCanBeDefined() throws Exception { - this.contextLoader.config(SpecificCacheResolverConfiguration.class) - .env("spring.cache.type=simple").load(context -> { - validateCacheManager(context, ConcurrentMapCacheManager.class); - assertThat(context.getBeansOfType(CacheResolver.class)).hasSize(1); + this.context.withUserConfiguration(SpecificCacheResolverConfiguration.class) + .withPropertyValues("spring.cache.type=simple").run((loaded) -> { + getCacheManager(loaded, ConcurrentMapCacheManager.class); + assertThat(loaded).getBeans(CacheResolver.class).hasSize(1); }); } @Test public void notSupportedCachingMode() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=foobar").loadAndFail(BeanCreationException.class, - ex -> assertThat(ex.getMessage()).contains( - "Failed to bind properties under 'spring.cache.type'")); + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=foobar").run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining( + "Failed to bind properties under 'spring.cache.type'"); + }); } @Test public void simpleCacheExplicit() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=simple").load(context -> { - ConcurrentMapCacheManager cacheManager = validateCacheManager(context, - ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=simple").run((loaded) -> { + assertThat(getCacheManager(loaded, ConcurrentMapCacheManager.class) + .getCacheNames()).isEmpty(); }); } @Test public void simpleCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "simple", - "allCacheManagerCustomizer", "simpleCacheManagerCustomizer"); + this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "simple") + .run(dunno("allCacheManagerCustomizer", "simpleCacheManagerCustomizer")); } @Test public void simpleCacheExplicitWithCacheNames() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=simple", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - ConcurrentMapCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + ConcurrentMapCacheManager cacheManager = getCacheManager(loaded, ConcurrentMapCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); @@ -187,50 +191,56 @@ public class CacheAutoConfigurationTests { @Test public void genericCacheWithCaches() { - this.contextLoader.config(GenericCacheConfiguration.class).load(context -> { - SimpleCacheManager cacheManager = validateCacheManager(context, - SimpleCacheManager.class); - assertThat(cacheManager.getCache("first")) - .isEqualTo(context.getBean("firstCache")); - assertThat(cacheManager.getCache("second")) - .isEqualTo(context.getBean("secondCache")); - assertThat(cacheManager.getCacheNames()).hasSize(2); - }); + this.context.withUserConfiguration(GenericCacheConfiguration.class) + .run((loaded) -> { + SimpleCacheManager cacheManager = getCacheManager(loaded, + SimpleCacheManager.class); + assertThat(cacheManager.getCache("first")) + .isEqualTo(loaded.getBean("firstCache")); + assertThat(cacheManager.getCache("second")) + .isEqualTo(loaded.getBean("secondCache")); + assertThat(cacheManager.getCacheNames()).hasSize(2); + }); } @Test public void genericCacheExplicit() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=generic").loadAndFail(BeanCreationException.class, - ex -> assertThat(ex.getMessage()).contains( - "No cache manager could be auto-configured", "GENERIC")); + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=generic").run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining( + "No cache manager could be auto-configured") + .hasMessageContaining("GENERIC"); + }); } @Test public void genericCacheWithCustomizers() { - testCustomizers(GenericCacheAndCustomizersConfiguration.class, "generic", - "allCacheManagerCustomizer", "genericCacheManagerCustomizer"); + this.context.withUserConfiguration(GenericCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "generic") + .run(dunno("allCacheManagerCustomizer", "genericCacheManagerCustomizer")); } @Test public void genericCacheExplicitWithCaches() { - this.contextLoader.config(GenericCacheConfiguration.class) - .env("spring.cache.type=generic").load(context -> { - SimpleCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(GenericCacheConfiguration.class) + .withPropertyValues("spring.cache.type=generic").run((loaded) -> { + SimpleCacheManager cacheManager = getCacheManager(loaded, SimpleCacheManager.class); assertThat(cacheManager.getCache("first")) - .isEqualTo(context.getBean("firstCache")); + .isEqualTo(loaded.getBean("firstCache")); assertThat(cacheManager.getCache("second")) - .isEqualTo(context.getBean("secondCache")); + .isEqualTo(loaded.getBean("secondCache")); assertThat(cacheManager.getCacheNames()).hasSize(2); }); } @Test public void couchbaseCacheExplicit() { - this.contextLoader.config(CouchbaseCacheConfiguration.class) - .env("spring.cache.type=couchbase").load(context -> { - CouchbaseCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(CouchbaseCacheConfiguration.class) + .withPropertyValues("spring.cache.type=couchbase").run((loaded) -> { + CouchbaseCacheManager cacheManager = getCacheManager(loaded, CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); }); @@ -238,70 +248,77 @@ public class CacheAutoConfigurationTests { @Test public void couchbaseCacheWithCustomizers() { - testCustomizers(CouchbaseCacheAndCustomizersConfiguration.class, "couchbase", - "allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer"); + this.context + .withUserConfiguration(CouchbaseCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "couchbase").run(dunno( + "allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer")); } @Test public void couchbaseCacheExplicitWithCaches() { - this.contextLoader.config(CouchbaseCacheConfiguration.class) - .env("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", + this.context.withUserConfiguration(CouchbaseCacheConfiguration.class) + .withPropertyValues("spring.cache.type=couchbase", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - CouchbaseCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + CouchbaseCacheManager cacheManager = getCacheManager(loaded, CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache cache = cacheManager.getCache("foo"); assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(0); assertThat(((CouchbaseCache) cache).getNativeCache()) - .isEqualTo(context.getBean("bucket")); + .isEqualTo(loaded.getBean("bucket")); }); } @Test public void couchbaseCacheExplicitWithTtl() { - this.contextLoader.config(CouchbaseCacheConfiguration.class) - .env("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", + this.context.withUserConfiguration(CouchbaseCacheConfiguration.class) + .withPropertyValues("spring.cache.type=couchbase", + "spring.cache.cacheNames=foo,bar", "spring.cache.couchbase.expiration=2000") - .load(context -> { - CouchbaseCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + CouchbaseCacheManager cacheManager = getCacheManager(loaded, CouchbaseCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache cache = cacheManager.getCache("foo"); assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(2); assertThat(((CouchbaseCache) cache).getNativeCache()) - .isEqualTo(context.getBean("bucket")); + .isEqualTo(loaded.getBean("bucket")); }); } @Test public void redisCacheExplicit() { - this.contextLoader.config(RedisCacheConfiguration.class) - .env("spring.cache.type=redis").load(context -> { - RedisCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(RedisCacheConfiguration.class) + .withPropertyValues("spring.cache.type=redis").run((loaded) -> { + RedisCacheManager cacheManager = getCacheManager(loaded, RedisCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); - assertThat(((org.springframework.data.redis.cache.RedisCacheConfiguration) - new DirectFieldAccessor(cacheManager).getPropertyValue( - "defaultCacheConfig")).usePrefix()).isTrue(); + assertThat( + ((org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor( + cacheManager).getPropertyValue("defaultCacheConfig")) + .usePrefix()).isTrue(); }); } @Test public void redisCacheWithCustomizers() { - testCustomizers(RedisCacheAndCustomizersConfiguration.class, "redis", - "allCacheManagerCustomizer", "redisCacheManagerCustomizer"); + this.context.withUserConfiguration(RedisCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "redis") + .run(dunno("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); } @Test public void redisCacheExplicitWithCaches() { - this.contextLoader.config(RedisCacheConfiguration.class) - .env("spring.cache.type=redis", "spring.cache.cacheNames[0]=foo", + this.context.withUserConfiguration(RedisCacheConfiguration.class) + .withPropertyValues("spring.cache.type=redis", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - RedisCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + RedisCacheManager cacheManager = getCacheManager(loaded, RedisCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); @@ -309,9 +326,9 @@ public class CacheAutoConfigurationTests { @Test public void noOpCacheExplicit() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=none").load(context -> { - NoOpCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=none").run((loaded) -> { + NoOpCacheManager cacheManager = getCacheManager(loaded, NoOpCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); }); @@ -319,25 +336,27 @@ public class CacheAutoConfigurationTests { @Test public void jCacheCacheNoProviderExplicit() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache").loadAndFail(ex -> { - assertThat(ex).isInstanceOf(BeanCreationException.class); - assertThat(ex.getMessage()).contains( - "No cache manager could be auto-configured", "JCACHE"); + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache").run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining( + "No cache manager could be auto-configured") + .hasMessageContaining("JCACHE"); }); } @Test public void jCacheCacheWithProvider() { String cachingProviderFqn = MockCachingProvider.class.getName(); - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).isEmpty(); - assertThat(context.getBean(javax.cache.CacheManager.class)) + assertThat(loaded.getBean(javax.cache.CacheManager.class)) .isEqualTo(cacheManager.getCacheManager()); }); } @@ -345,13 +364,13 @@ public class CacheAutoConfigurationTests { @Test public void jCacheCacheWithCaches() { String cachingProviderFqn = MockCachingProvider.class.getName(); - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); @@ -360,16 +379,16 @@ public class CacheAutoConfigurationTests { @Test public void jCacheCacheWithCachesAndCustomConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); - this.contextLoader.config(JCacheCustomConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(JCacheCustomConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two") - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); - CompleteConfiguration defaultCacheConfiguration = context + CompleteConfiguration defaultCacheConfiguration = loaded .getBean(CompleteConfiguration.class); verify(cacheManager.getCacheManager()).createCache("one", defaultCacheConfiguration); @@ -380,35 +399,38 @@ public class CacheAutoConfigurationTests { @Test public void jCacheCacheWithExistingJCacheManager() { - this.contextLoader.config(JCacheCustomCacheManager.class) - .env("spring.cache.type=jcache").load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(JCacheCustomCacheManager.class) + .withPropertyValues("spring.cache.type=jcache").run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); assertThat(cacheManager.getCacheManager()) - .isEqualTo(context.getBean("customJCacheCacheManager")); + .isEqualTo(loaded.getBean("customJCacheCacheManager")); }); } @Test public void jCacheCacheWithUnknownProvider() { - String wrongCachingProviderFqn = "org.acme.FooBar"; - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + wrongCachingProviderFqn) - .loadAndFail(BeanCreationException.class, ex -> assertThat( - ex.getMessage().contains(wrongCachingProviderFqn))); + String wrongCachingProviderClassName = "org.acme.FooBar"; + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", + "spring.cache.jcache.provider=" + wrongCachingProviderClassName) + .run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining(wrongCachingProviderClassName); + }); } @Test public void jCacheCacheWithConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; - this.contextLoader.config(JCacheCustomConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(JCacheCustomConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); assertThat(cacheManager.getCacheManager().getURI()) @@ -420,41 +442,45 @@ public class CacheAutoConfigurationTests { public void jCacheCacheWithWrongConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/cache/does-not-exist.xml"; - this.contextLoader.config(JCacheCustomConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(JCacheCustomConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) - .loadAndFail(BeanCreationException.class, - ex -> assertThat(ex.getMessage()).contains("does not exist", - configLocation)); + .run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("does not exist") + .hasMessageContaining(configLocation); + }); } @Test public void ehcacheCacheWithCaches() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=ehcache").load(context -> { - EhCacheCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=ehcache").run((loaded) -> { + EhCacheCacheManager cacheManager = getCacheManager(loaded, EhCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", "cacheTest2"); - assertThat(context.getBean(net.sf.ehcache.CacheManager.class)) + assertThat(loaded.getBean(net.sf.ehcache.CacheManager.class)) .isEqualTo(cacheManager.getCacheManager()); }); } @Test public void ehcacheCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "ehcache", - "allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer"); + this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "ehcache") + .run(dunno("allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer")); } @Test public void ehcacheCacheWithConfig() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=ehcache", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=ehcache", "spring.cache.ehcache.config=cache/ehcache-override.xml") - .load(context -> { - EhCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + EhCacheCacheManager cacheManager = getCacheManager(loaded, EhCacheCacheManager.class); assertThat(cacheManager.getCacheNames()) .containsOnly("cacheOverrideTest1", "cacheOverrideTest2"); @@ -463,25 +489,25 @@ public class CacheAutoConfigurationTests { @Test public void ehcacheCacheWithExistingCacheManager() { - this.contextLoader.config(EhCacheCustomCacheManager.class) - .env("spring.cache.type=ehcache").load(context -> { - EhCacheCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(EhCacheCustomCacheManager.class) + .withPropertyValues("spring.cache.type=ehcache").run((loaded) -> { + EhCacheCacheManager cacheManager = getCacheManager(loaded, EhCacheCacheManager.class); assertThat(cacheManager.getCacheManager()) - .isEqualTo(context.getBean("customEhCacheCacheManager")); + .isEqualTo(loaded.getBean("customEhCacheCacheManager")); }); } @Test public void ehcache3AsJCacheWithCaches() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); }); @@ -491,12 +517,12 @@ public class CacheAutoConfigurationTests { public void ehcache3AsJCacheWithConfig() throws IOException { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); @@ -508,48 +534,54 @@ public class CacheAutoConfigurationTests { @Test public void hazelcastCacheExplicit() { - this.contextLoader.autoConfigFirst(HazelcastAutoConfiguration.class) - .config(DefaultCacheConfiguration.class) - .env("spring.cache.type=hazelcast").load(context -> { - HazelcastCacheManager cacheManager = validateCacheManager(context, + this.context + .withConfiguration( + AutoConfigurations.of(HazelcastAutoConfiguration.class)) + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=hazelcast").run((loaded) -> { + HazelcastCacheManager cacheManager = getCacheManager(loaded, HazelcastCacheManager.class); // NOTE: the hazelcast implementation knows about a cache in a lazy // manner. cacheManager.getCache("defaultCache"); assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); - assertThat(context.getBean(HazelcastInstance.class)) + assertThat(loaded.getBean(HazelcastInstance.class)) .isEqualTo(cacheManager.getHazelcastInstance()); }); } @Test public void hazelcastCacheWithCustomizers() { - testCustomizers(HazelcastCacheAndCustomizersConfiguration.class, "hazelcast", - "allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer"); + this.context + .withUserConfiguration(HazelcastCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "hazelcast").run(dunno( + "allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer")); } @Test public void hazelcastCacheWithExistingHazelcastInstance() { - this.contextLoader.config(HazelcastCustomHazelcastInstance.class) - .env("spring.cache.type=hazelcast").load(context -> { - HazelcastCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(HazelcastCustomHazelcastInstance.class) + .withPropertyValues("spring.cache.type=hazelcast").run((loaded) -> { + HazelcastCacheManager cacheManager = getCacheManager(loaded, HazelcastCacheManager.class); assertThat(cacheManager.getHazelcastInstance()) - .isEqualTo(context.getBean("customHazelcastInstance")); + .isEqualTo(loaded.getBean("customHazelcastInstance")); }); } @Test public void hazelcastCacheWithHazelcastAutoConfiguration() throws IOException { String hazelcastConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; - this.contextLoader.autoConfigFirst(HazelcastAutoConfiguration.class) - .config(DefaultCacheConfiguration.class) - .env("spring.cache.type=hazelcast", + this.context + .withConfiguration( + AutoConfigurations.of(HazelcastAutoConfiguration.class)) + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=hazelcast", "spring.hazelcast.config=" + hazelcastConfig) - .load(context -> { - HazelcastCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + HazelcastCacheManager cacheManager = getCacheManager(loaded, HazelcastCacheManager.class); - HazelcastInstance hazelcastInstance = context + HazelcastInstance hazelcastInstance = loaded .getBean(HazelcastInstance.class); assertThat(cacheManager.getHazelcastInstance()) .isSameAs(hazelcastInstance); @@ -564,13 +596,13 @@ public class CacheAutoConfigurationTests { public void hazelcastAsJCacheWithCaches() { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); try { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); @@ -587,14 +619,13 @@ public class CacheAutoConfigurationTests { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); try { String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.config=" + configLocation) - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); - Resource configResource = new ClassPathResource(configLocation); assertThat(cacheManager.getCacheManager().getURI()) .isEqualTo(configResource.getURI()); @@ -609,20 +640,21 @@ public class CacheAutoConfigurationTests { @Test public void hazelcastAsJCacheWithExistingHazelcastInstance() throws IOException { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); - this.contextLoader.autoConfig(HazelcastAutoConfiguration.class) - .config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", + this.context + .withConfiguration( + AutoConfigurations.of(HazelcastAutoConfiguration.class)) + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, + .run((loaded) -> { + JCacheCacheManager cacheManager = getCacheManager(loaded, JCacheCacheManager.class); javax.cache.CacheManager jCacheManager = cacheManager .getCacheManager(); assertThat(jCacheManager).isInstanceOf( com.hazelcast.cache.HazelcastCacheManager.class); - assertThat(context.getBeansOfType(HazelcastInstance.class)) - .hasSize(1); - HazelcastInstance hazelcastInstance = context + assertThat(loaded.getBeansOfType(HazelcastInstance.class)).hasSize(1); + HazelcastInstance hazelcastInstance = loaded .getBean(HazelcastInstance.class); assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager) .getHazelcastInstance()).isSameAs(hazelcastInstance); @@ -633,113 +665,108 @@ public class CacheAutoConfigurationTests { @Test public void infinispanCacheWithConfig() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=infinispan", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml") - .load(context -> { - SpringEmbeddedCacheManager cacheManager = validateCacheManager( - context, SpringEmbeddedCacheManager.class); + .run((loaded) -> { + SpringEmbeddedCacheManager cacheManager = getCacheManager(loaded, + SpringEmbeddedCacheManager.class); assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); }); } @Test public void infinispanCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "infinispan", - "allCacheManagerCustomizer", "infinispanCacheManagerCustomizer"); + this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "infinispan").run(dunno( + "allCacheManagerCustomizer", "infinispanCacheManagerCustomizer")); } @Test public void infinispanCacheWithCaches() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=infinispan", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - SpringEmbeddedCacheManager cacheManager = validateCacheManager( - context, SpringEmbeddedCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + .run((loaded) -> { + assertThat(getCacheManager(loaded, SpringEmbeddedCacheManager.class) + .getCacheNames()).containsOnly("foo", "bar"); }); } @Test public void infinispanCacheWithCachesAndCustomConfig() { - this.contextLoader.config(InfinispanCustomConfiguration.class) - .env("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + this.context.withUserConfiguration(InfinispanCustomConfiguration.class) + .withPropertyValues("spring.cache.type=infinispan", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - SpringEmbeddedCacheManager cacheManager = validateCacheManager( - context, SpringEmbeddedCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - ConfigurationBuilder defaultConfigurationBuilder = context - .getBean(ConfigurationBuilder.class); - verify(defaultConfigurationBuilder, times(2)).build(); + .run((loaded) -> { + assertThat(getCacheManager(loaded, SpringEmbeddedCacheManager.class) + .getCacheNames()).containsOnly("foo", "bar"); + verify(loaded.getBean(ConfigurationBuilder.class), times(2)).build(); }); } @Test public void infinispanAsJCacheWithCaches() { - String cachingProviderFqn = JCachingProvider.class.getName(); - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, + String cachingProviderClassName = JCachingProvider.class.getName(); + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", + "spring.cache.jcache.provider=" + cachingProviderClassName, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, - JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + .run((loaded) -> { + assertThat(getCacheManager(loaded, JCacheCacheManager.class) + .getCacheNames()).containsOnly("foo", "bar"); }); } @Test public void infinispanAsJCacheWithConfig() throws IOException { - String cachingProviderFqn = JCachingProvider.class.getName(); + String cachingProviderClassName = JCachingProvider.class.getName(); String configLocation = "infinispan.xml"; - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", + "spring.cache.jcache.provider=" + cachingProviderClassName, "spring.cache.jcache.config=" + configLocation) - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, - JCacheCacheManager.class); - + .run((loaded) -> { Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); + assertThat(getCacheManager(loaded, JCacheCacheManager.class) + .getCacheManager().getURI()) + .isEqualTo(configResource.getURI()); }); } @Test public void jCacheCacheWithCachesAndCustomizer() { - String cachingProviderFqn = HazelcastCachingProvider.class.getName(); + String cachingProviderClassName = HazelcastCachingProvider.class.getName(); try { - this.contextLoader.config(JCacheWithCustomizerConfiguration.class) - .env("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, + this.context.withUserConfiguration(JCacheWithCustomizerConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", + "spring.cache.jcache.provider=" + cachingProviderClassName, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(context -> { - JCacheCacheManager cacheManager = validateCacheManager(context, - JCacheCacheManager.class); + .run((loaded) -> { // see customizer - assertThat(cacheManager.getCacheNames()).containsOnly("foo", - "custom1"); + assertThat(getCacheManager(loaded, JCacheCacheManager.class) + .getCacheNames()).containsOnly("foo", "custom1"); }); } finally { - Caching.getCachingProvider(cachingProviderFqn).close(); + Caching.getCachingProvider(cachingProviderClassName).close(); } } @Test public void caffeineCacheWithExplicitCaches() { - this.contextLoader.config(DefaultCacheConfiguration.class) - .env("spring.cache.type=caffeine", "spring.cache.cacheNames=foo") - .load(context -> { - CaffeineCacheManager cacheManager = validateCacheManager(context, + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=caffeine", + "spring.cache.cacheNames=foo") + .run((loaded) -> { + CaffeineCacheManager manager = getCacheManager(loaded, CaffeineCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo"); - Cache foo = cacheManager.getCache("foo"); + assertThat(manager.getCacheNames()).containsOnly("foo"); + Cache foo = manager.getCache("foo"); foo.get("1"); // See next tests: no spec given so stats should be disabled assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) @@ -749,74 +776,75 @@ public class CacheAutoConfigurationTests { @Test public void caffeineCacheWithCustomizers() { - testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "caffeine", - "allCacheManagerCustomizer", "caffeineCacheManagerCustomizer"); + this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) + .withPropertyValues("spring.cache.type=" + "caffeine").run(dunno( + "allCacheManagerCustomizer", "caffeineCacheManagerCustomizer")); } @Test public void caffeineCacheWithExplicitCacheBuilder() { - this.contextLoader.config(CaffeineCacheBuilderConfiguration.class) - .env("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") - .load(this::validateCaffeineCacheWithStats); + this.context.withUserConfiguration(CaffeineCacheBuilderConfiguration.class) + .withPropertyValues("spring.cache.type=caffeine", + "spring.cache.cacheNames=foo,bar") + .run(this::validateCaffeineCacheWithStats); } @Test public void caffeineCacheExplicitWithSpec() { - this.contextLoader.config(CaffeineCacheSpecConfiguration.class) - .env("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", + this.context.withUserConfiguration(CaffeineCacheSpecConfiguration.class) + .withPropertyValues("spring.cache.type=caffeine", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(this::validateCaffeineCacheWithStats); + .run(this::validateCaffeineCacheWithStats); } @Test public void caffeineCacheExplicitWithSpecString() { - this.contextLoader.config(DefaultCacheConfiguration.class).env( - "spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .load(this::validateCaffeineCacheWithStats); + this.context.withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=caffeine", + "spring.cache.caffeine.spec=recordStats", + "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run(this::validateCaffeineCacheWithStats); } - private void validateCaffeineCacheWithStats(ConfigurableApplicationContext context) { - CaffeineCacheManager cacheManager = validateCacheManager(context, + private void validateCaffeineCacheWithStats(AssertableApplicationContext context) { + CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - Cache foo = cacheManager.getCache("foo"); + assertThat(manager.getCacheNames()).containsOnly("foo", "bar"); + Cache foo = manager.getCache("foo"); foo.get("1"); assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) .isEqualTo(1L); } - private T validateCacheManager( - ConfigurableApplicationContext context, Class type) { - CacheManager cacheManager = context.getBean(CacheManager.class); - assertThat(cacheManager).as("Wrong cache manager type").isInstanceOf(type); - return type.cast(cacheManager); - } - @SuppressWarnings("rawtypes") - private void testCustomizers(Class config, String cacheType, + private ContextConsumer dunno( String... expectedCustomizerNames) { - this.contextLoader.config(config).env("spring.cache.type=" + cacheType) - .load(context -> { - CacheManager cacheManager = validateCacheManager(context, - CacheManager.class); - List expected = new ArrayList<>(); - expected.addAll(Arrays.asList(expectedCustomizerNames)); - Map map = context - .getBeansOfType(CacheManagerTestCustomizer.class); - for (Map.Entry entry : map - .entrySet()) { - if (expected.contains(entry.getKey())) { - expected.remove(entry.getKey()); - assertThat(entry.getValue().cacheManager) - .isSameAs(cacheManager); - } - else { - assertThat(entry.getValue().cacheManager).isNull(); - } - } - assertThat(expected).hasSize(0); - }); + return (loaded) -> { + CacheManager cacheManager = getCacheManager(loaded, CacheManager.class); + List expected = new ArrayList<>( + Arrays.asList(expectedCustomizerNames)); + Map customizer = loaded + .getBeansOfType(CacheManagerTestCustomizer.class); + customizer.forEach((key, value) -> { + if (expected.contains(key)) { + expected.remove(key); + assertThat(value.cacheManager).isSameAs(cacheManager); + } + else { + assertThat(value.cacheManager).isNull(); + } + }); + assertThat(expected).hasSize(0); + }; + } + + private T getCacheManager( + AssertableApplicationContext loaded, Class type) { + CacheManager cacheManager = loaded.getBean(CacheManager.class); + assertThat(cacheManager).as("Wrong cache manager type").isInstanceOf(type); + return type.cast(cacheManager); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java index eb25ef48670..9989fe1dc9f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java @@ -23,12 +23,14 @@ import com.hazelcast.client.impl.HazelcastClientProxy; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; +import org.assertj.core.api.Condition; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.ApplicationContextTester; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -59,68 +61,72 @@ public class HazelcastAutoConfigurationClientTests { } } - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(HazelcastAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test public void systemProperty() throws IOException { - this.contextLoader - .systemProperty(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY, - "classpath:org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-client-specific.xml") - .load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance) - .isInstanceOf(HazelcastClientProxy.class); - assertThat(hazelcastInstance.getName()).startsWith("hz.client_"); + this.context + .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/" + + "hazelcast-client-specific.xml") + .run((loaded) -> { + assertThat(loaded).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastInstance.class) + .has(nameStartingWith("hz.client_")); }); } @Test public void explicitConfigFile() throws IOException { - this.contextLoader - .env("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.xml") - .load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance) - .isInstanceOf(HazelcastClientProxy.class); - assertThat(hazelcastInstance.getName()).startsWith("hz.client_"); + this.context + .withPropertyValues( + "spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.xml") + .run((loaded) -> { + assertThat(loaded).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastClientProxy.class) + .has(nameStartingWith("hz.client_")); }); } @Test public void explicitConfigUrl() throws IOException { - this.contextLoader.env("spring.hazelcast.config=hazelcast-client-default.xml") - .load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance) - .isInstanceOf(HazelcastClientProxy.class); - assertThat(hazelcastInstance.getName()).startsWith("hz.client_"); + this.context + .withPropertyValues( + "spring.hazelcast.config=hazelcast-client-default.xml") + .run((loaded) -> { + assertThat(loaded).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastClientProxy.class) + .has(nameStartingWith("hz.client_")); }); } @Test public void unknownConfigFile() { - this.contextLoader.env("spring.hazelcast.config=foo/bar/unknown.xml").loadAndFail( - BeanCreationException.class, - ex -> assertThat(ex.getMessage()).contains("foo/bar/unknown.xml")); + this.context.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") + .run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("foo/bar/unknown.xml"); + }); } @Test public void clientConfigTakesPrecedence() { - this.contextLoader.config(HazelcastServerAndClientConfig.class) - .env("spring.hazelcast.config=this-is-ignored.xml").load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance) + this.context.withUserConfiguration(HazelcastServerAndClientConfig.class) + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((loaded) -> { + assertThat(loaded).getBean(HazelcastInstance.class) .isInstanceOf(HazelcastClientProxy.class); }); } + private Condition nameStartingWith(String prefix) { + return new Condition((o) -> o.getName().startsWith(prefix), + "Name starts with " + prefix); + } + @Configuration static class HazelcastServerAndClientConfig { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java index 4f5ada425d7..756dfafa58d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java @@ -27,7 +27,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.ApplicationContextTester; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.context.annotation.Bean; @@ -45,44 +46,38 @@ import static org.assertj.core.api.Assertions.assertThat; @ClassPathExclusions("hazelcast-client-*.jar") public class HazelcastAutoConfigurationServerTests { - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(HazelcastAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test public void defaultConfigFile() throws IOException { // hazelcast.xml present in root classpath - this.contextLoader.load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) + this.context.run((loaded) -> { + Config config = loaded.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getConfigurationUrl()) .isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); }); } @Test public void systemProperty() throws IOException { - this.contextLoader - .systemProperty(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY, - "classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") - .load(context -> { - - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - Map queueConfigs = hazelcastInstance.getConfig() - .getQueueConfigs(); - assertThat(queueConfigs).hasSize(1).containsKey("foobar"); + this.context + .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") + .run((loaded) -> { + Config config = loaded.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getQueueConfigs().keySet()).containsOnly("foobar"); }); } @Test public void explicitConfigFile() throws IOException { - this.contextLoader - .env("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + this.context.withPropertyValues( + "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.xml") - .load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getConfigurationFile()) + .run((loaded) -> { + Config config = loaded.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getConfigurationFile()) .isEqualTo(new ClassPathResource( "org/springframework/boot/autoconfigure/hazelcast" + "/hazelcast-specific.xml").getFile()); @@ -91,54 +86,53 @@ public class HazelcastAutoConfigurationServerTests { @Test public void explicitConfigUrl() throws IOException { - this.contextLoader.env("spring.hazelcast.config=hazelcast-default.xml") - .load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) - .isEqualTo(new ClassPathResource("hazelcast-default.xml") - .getURL()); + this.context.withPropertyValues("spring.hazelcast.config=hazelcast-default.xml") + .run((loaded) -> { + Config config = loaded.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getConfigurationUrl()).isEqualTo( + new ClassPathResource("hazelcast-default.xml").getURL()); }); } @Test public void unknownConfigFile() { - this.contextLoader.env("spring.hazelcast.config=foo/bar/unknown.xml").loadAndFail( - BeanCreationException.class, - ex -> assertThat(ex.getMessage()).contains("foo/bar/unknown.xml")); + this.context.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") + .run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("foo/bar/unknown.xml"); + }); } @Test public void configInstanceWithName() { Config config = new Config("my-test-instance"); - HazelcastInstance existingHazelcastInstance = Hazelcast - .newHazelcastInstance(config); + HazelcastInstance existing = Hazelcast.newHazelcastInstance(config); try { - this.contextLoader.config(HazelcastConfigWithName.class) - .env("spring.hazelcast.config=this-is-ignored.xml").load(context -> { - HazelcastInstance hazelcastInstance = context + this.context.withUserConfiguration(HazelcastConfigWithName.class) + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run(loaded -> { + HazelcastInstance hazelcast = (loaded) .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getInstanceName()) + assertThat(hazelcast.getConfig().getInstanceName()) .isEqualTo("my-test-instance"); // Should reuse any existing instance by default. - assertThat(hazelcastInstance) - .isEqualTo(existingHazelcastInstance); + assertThat(hazelcast).isEqualTo(existing); }); } finally { - existingHazelcastInstance.shutdown(); + existing.shutdown(); } } @Test public void configInstanceWithoutName() { - this.contextLoader.config(HazelcastConfigNoName.class) - .env("spring.hazelcast.config=this-is-ignored.xml").load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - Map queueConfigs = hazelcastInstance.getConfig() - .getQueueConfigs(); - assertThat(queueConfigs).hasSize(1).containsKey("another-queue"); + this.context.withUserConfiguration(HazelcastConfigNoName.class) + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((loaded) -> { + Config config = loaded.getBean(HazelcastInstance.class).getConfig(); + Map queueConfigs = config.getQueueConfigs(); + assertThat(queueConfigs.keySet()).containsOnly("another-queue"); }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java index 304fe706bca..c074207884c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java @@ -18,10 +18,12 @@ package org.springframework.boot.autoconfigure.hazelcast; import java.io.IOException; +import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import org.junit.Test; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.ApplicationContextTester; import org.springframework.core.io.ClassPathResource; import static org.assertj.core.api.Assertions.assertThat; @@ -33,16 +35,15 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class HazelcastAutoConfigurationTests { - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(HazelcastAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test public void defaultConfigFile() throws IOException { // no hazelcast-client.xml and hazelcast.xml is present in root classpath - this.contextLoader.load(context -> { - HazelcastInstance hazelcastInstance = context - .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) + this.context.run((loaded) -> { + Config config = loaded.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getConfigurationUrl()) .isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java index b012d4cde67..68b1ce5d73a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java @@ -37,9 +37,10 @@ import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.jdbc.DatabaseDriver; -import org.springframework.boot.test.context.ContextConsumer; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.test.context.ApplicationContextTester; +import org.springframework.boot.test.context.AssertableApplicationContext; import org.springframework.boot.test.context.HidePackagesClassLoader; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -57,22 +58,22 @@ import static org.mockito.Mockito.mock; */ public class DataSourceAutoConfigurationTests { - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(DataSourceAutoConfiguration.class) - .env("spring.datasource.initialize=false", + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.initialize=false", "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); @Test public void testDefaultDataSourceExists() throws Exception { - this.contextLoader.load( - context -> assertThat(context.getBean(DataSource.class)).isNotNull()); + this.context + .run((loaded) -> assertThat(loaded).hasSingleBean(DataSource.class)); } @Test public void testDataSourceHasEmbeddedDefault() throws Exception { - this.contextLoader.load(context -> { - HikariDataSource dataSource = context.getBean(HikariDataSource.class); + this.context.run((loaded) -> { + HikariDataSource dataSource = loaded.getBean(HikariDataSource.class); assertThat(dataSource.getJdbcUrl()).isNotNull(); assertThat(dataSource.getDriverClassName()).isNotNull(); }); @@ -82,8 +83,11 @@ public class DataSourceAutoConfigurationTests { public void testBadUrl() throws Exception { try { EmbeddedDatabaseConnection.override = EmbeddedDatabaseConnection.NONE; - this.contextLoader.env("spring.datasource.url:jdbc:not-going-to-work") - .loadAndFail(BeanCreationException.class, ex -> { + this.context + .withPropertyValues("spring.datasource.url:jdbc:not-going-to-work") + .run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class); }); } finally { @@ -93,10 +97,14 @@ public class DataSourceAutoConfigurationTests { @Test public void testBadDriverClass() throws Exception { - this.contextLoader.env("spring.datasource.driverClassName:org.none.jdbcDriver") - .loadAndFail(BeanCreationException.class, - ex -> assertThat(ex.getMessage()) - .contains("org.none.jdbcDriver")); + this.context + .withPropertyValues( + "spring.datasource.driverClassName:org.none.jdbcDriver") + .run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("org.none.jdbcDriver"); + }); } @Test @@ -111,14 +119,14 @@ public class DataSourceAutoConfigurationTests { public void tomcatIsFallback() throws Exception { assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, Collections.singletonList("com.zaxxer.hikari"), - dataSource -> assertThat(dataSource.getUrl()) + (dataSource) -> assertThat(dataSource.getUrl()) .startsWith("jdbc:hsqldb:mem:testdb")); } @Test public void tomcatValidatesConnectionByDefault() { assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, - Collections.singletonList("com.zaxxer.hikari"), dataSource -> { + Collections.singletonList("com.zaxxer.hikari"), (dataSource) -> { assertThat(dataSource.isTestOnBorrow()).isTrue(); assertThat(dataSource.getValidationQuery()) .isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); @@ -129,14 +137,14 @@ public class DataSourceAutoConfigurationTests { public void commonsDbcp2IsFallback() throws Exception { assertDataSource(BasicDataSource.class, Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), - dataSource -> assertThat(dataSource.getUrl()) + (dataSource) -> assertThat(dataSource.getUrl()) .startsWith("jdbc:hsqldb:mem:testdb")); } @Test public void commonsDbcp2ValidatesConnectionByDefault() throws Exception { assertDataSource(org.apache.commons.dbcp2.BasicDataSource.class, - Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), dataSource -> { + Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), (dataSource) -> { assertThat(dataSource.getTestOnBorrow()).isEqualTo(true); assertThat(dataSource.getValidationQuery()).isNull(); // Use // Connection#isValid() @@ -144,12 +152,12 @@ public class DataSourceAutoConfigurationTests { } @Test + @SuppressWarnings("resource") public void testEmbeddedTypeDefaultsUsername() throws Exception { - this.contextLoader.env("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", - "spring.datasource.url:jdbc:hsqldb:mem:testdb").load(context -> { - DataSource bean = context.getBean(DataSource.class); - assertThat(bean).isNotNull(); - @SuppressWarnings("resource") + this.context.withPropertyValues( + "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + "spring.datasource.url:jdbc:hsqldb:mem:testdb").run((loaded) -> { + DataSource bean = loaded.getBean(DataSource.class); HikariDataSource pool = (HikariDataSource) bean; assertThat(pool.getDriverClassName()) .isEqualTo("org.hsqldb.jdbcDriver"); @@ -163,62 +171,62 @@ public class DataSourceAutoConfigurationTests { */ @Test public void explicitTypeNoSupportedDataSource() { - this.contextLoader - .classLoader(new HidePackagesClassLoader("org.apache.tomcat", + this.context + .withClassLoader(new HidePackagesClassLoader("org.apache.tomcat", "com.zaxxer.hikari", "org.apache.commons.dbcp", "org.apache.commons.dbcp2")) - .env("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + .withPropertyValues( + "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb", "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) - .load(testExplicitType()); + .run(this::containsOnlySimpleDriverDataSource); } @Test public void explicitTypeSupportedDataSource() { - this.contextLoader - .env("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + this.context + .withPropertyValues( + "spring.datasource.driverClassName:org.hsqldb.jdbcDriver", "spring.datasource.url:jdbc:hsqldb:mem:testdb", "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) - .load(testExplicitType()); + .run(this::containsOnlySimpleDriverDataSource); } - private ContextConsumer testExplicitType() { - return context -> { - assertThat(context.getBeansOfType(DataSource.class)).hasSize(1); - DataSource bean = context.getBean(DataSource.class); - assertThat(bean).isNotNull(); - assertThat(bean.getClass()).isEqualTo(SimpleDriverDataSource.class); - }; + private void containsOnlySimpleDriverDataSource(AssertableApplicationContext loaded) { + assertThat(loaded).hasSingleBean(DataSource.class); + assertThat(loaded).getBean(DataSource.class) + .isExactlyInstanceOf(SimpleDriverDataSource.class); } @Test public void testExplicitDriverClassClearsUsername() throws Exception { - this.contextLoader.env( + this.context.withPropertyValues( "spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), - "spring.datasource.url:jdbc:foo://localhost").load(context -> { - DataSource dataSource = context.getBean(DataSource.class); - assertThat(dataSource).isNotNull(); - assertThat(((HikariDataSource) dataSource).getDriverClassName()) + "spring.datasource.url:jdbc:foo://localhost").run((loaded) -> { + assertThat(loaded).hasSingleBean(DataSource.class); + HikariDataSource dataSource = loaded.getBean(HikariDataSource.class); + assertThat(dataSource.getDriverClassName()) .isEqualTo(DatabaseTestDriver.class.getName()); - assertThat(((HikariDataSource) dataSource).getUsername()).isNull(); + assertThat(dataSource.getUsername()).isNull(); }); } @Test public void testDefaultDataSourceCanBeOverridden() throws Exception { - this.contextLoader.config(TestDataSourceConfiguration.class).load(context -> { - DataSource dataSource = context.getBean(DataSource.class); - assertThat(dataSource).isInstanceOf(BasicDataSource.class); - }); + this.context.withUserConfiguration(TestDataSourceConfiguration.class) + .run((loaded) -> { + assertThat(loaded).getBean(DataSource.class) + .isInstanceOf(BasicDataSource.class); + }); } @Test public void testDataSourceIsInitializedEarly() { - this.contextLoader.config(TestInitializedDataSourceConfiguration.class) - .env("spring.datasource.initialize=true") - .load(context -> assertThat(context + this.context.withUserConfiguration(TestInitializedDataSourceConfiguration.class) + .withPropertyValues("spring.datasource.initialize=true") + .run((loaded) -> assertThat(loaded .getBean(TestInitializedDataSourceConfiguration.class).called) .isTrue()); } @@ -227,8 +235,8 @@ public class DataSourceAutoConfigurationTests { List hiddenPackages, Consumer consumer) { HidePackagesClassLoader classLoader = new HidePackagesClassLoader( hiddenPackages.toArray(new String[hiddenPackages.size()])); - this.contextLoader.classLoader(classLoader).load(context -> { - DataSource bean = context.getBean(DataSource.class); + this.context.withClassLoader(classLoader).run((loaded) -> { + DataSource bean = loaded.getBean(DataSource.class); assertThat(bean).isInstanceOf(expectedType); consumer.accept(expectedType.cast(bean)); }); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java index 9dd0238f9ed..e16efb821b4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java @@ -26,8 +26,10 @@ import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.test.context.ApplicationContextTester; +import org.springframework.boot.test.context.AssertableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @@ -61,229 +63,213 @@ public class JmsAutoConfigurationTests { private static final String ACTIVEMQ_NETWORK_URL = "tcp://localhost:61616"; - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, + JmsAutoConfiguration.class)); @Test public void testDefaultJmsConfiguration() { - this.contextLoader.config(TestConfiguration.class).load(context -> { - ActiveMQConnectionFactory connectionFactory = context - .getBean(ActiveMQConnectionFactory.class); - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - JmsMessagingTemplate messagingTemplate = context - .getBean(JmsMessagingTemplate.class); - assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); - assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); - assertThat(context.containsBean("jmsListenerContainerFactory")).isTrue(); - }); + this.context.withUserConfiguration(TestConfiguration.class) + .run(this::testDefaultJmsConfiguration); + } + + private void testDefaultJmsConfiguration(AssertableApplicationContext loaded) { + ActiveMQConnectionFactory factory = loaded + .getBean(ActiveMQConnectionFactory.class); + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + JmsMessagingTemplate messagingTemplate = loaded + .getBean(JmsMessagingTemplate.class); + assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) + .getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); + assertThat(loaded.containsBean("jmsListenerContainerFactory")).isTrue(); } @Test public void testConnectionFactoryBackOff() { - this.contextLoader.config(TestConfiguration2.class) - .load(context -> assertThat( - context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) + this.context.withUserConfiguration(TestConfiguration2.class) + .run((loaded) -> assertThat( + loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) .isEqualTo("foobar")); } @Test public void testJmsTemplateBackOff() { - this.contextLoader.config(TestConfiguration3.class).load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getPriority()).isEqualTo(999); - }); + this.context.withUserConfiguration(TestConfiguration3.class).run( + (loaded) -> assertThat(loaded.getBean(JmsTemplate.class).getPriority()) + .isEqualTo(999)); } @Test public void testJmsMessagingTemplateBackOff() { - this.contextLoader.config(TestConfiguration5.class).load(context -> { - JmsMessagingTemplate messagingTemplate = context - .getBean(JmsMessagingTemplate.class); - assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); - }); + this.context.withUserConfiguration(TestConfiguration5.class) + .run((loaded) -> assertThat(loaded.getBean(JmsMessagingTemplate.class) + .getDefaultDestinationName()).isEqualTo("fooBar")); } @Test public void testJmsTemplateBackOffEverything() { - this.contextLoader.config(TestConfiguration2.class, TestConfiguration3.class, - TestConfiguration5.class).load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getPriority()).isEqualTo(999); - assertThat(context.getBean(ActiveMQConnectionFactory.class) - .getBrokerURL()).isEqualTo("foobar"); - JmsMessagingTemplate messagingTemplate = context - .getBean(JmsMessagingTemplate.class); - assertThat(messagingTemplate.getDefaultDestinationName()) - .isEqualTo("fooBar"); - assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); - }); + this.context + .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, + TestConfiguration5.class) + .run(this::testJmsTemplateBackOffEverything); + } + + private void testJmsTemplateBackOffEverything(AssertableApplicationContext loaded) { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + assertThat(jmsTemplate.getPriority()).isEqualTo(999); + assertThat(loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) + .isEqualTo("foobar"); + JmsMessagingTemplate messagingTemplate = loaded + .getBean(JmsMessagingTemplate.class); + assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); + assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); } @Test public void testEnableJmsCreateDefaultContainerFactory() { - this.contextLoader.config(EnableJmsConfiguration.class).load(context -> { - JmsListenerContainerFactory jmsListenerContainerFactory = context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); - }); + this.context.withUserConfiguration(EnableJmsConfiguration.class) + .run((loaded) -> assertThat(loaded) + .getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class) + .isExactlyInstanceOf(DefaultJmsListenerContainerFactory.class)); } @Test public void testJmsListenerContainerFactoryBackOff() { - this.contextLoader.config(TestConfiguration6.class, EnableJmsConfiguration.class) - .load(context -> { - JmsListenerContainerFactory jmsListenerContainerFactory = context - .getBean("jmsListenerContainerFactory", - JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(SimpleJmsListenerContainerFactory.class); - }); + this.context + .withUserConfiguration(TestConfiguration6.class, + EnableJmsConfiguration.class) + .run((loaded) -> assertThat(loaded) + .getBean("jmsListenerContainerFactory", + JmsListenerContainerFactory.class) + .isExactlyInstanceOf(SimpleJmsListenerContainerFactory.class)); } @Test public void testJmsListenerContainerFactoryWithCustomSettings() { - this.contextLoader.config(EnableJmsConfiguration.class) - .env("spring.jms.listener.autoStartup=false", + this.context.withUserConfiguration(EnableJmsConfiguration.class) + .withPropertyValues("spring.jms.listener.autoStartup=false", "spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.concurrency=2", "spring.jms.listener.maxConcurrency=10") - .load(context -> { - JmsListenerContainerFactory jmsListenerContainerFactory = context - .getBean("jmsListenerContainerFactory", - JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); - DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.isAutoStartup()).isFalse(); - assertThat(listenerContainer.getSessionAcknowledgeMode()) - .isEqualTo(Session.CLIENT_ACKNOWLEDGE); - assertThat(listenerContainer.getConcurrentConsumers()).isEqualTo(2); - assertThat(listenerContainer.getMaxConcurrentConsumers()) - .isEqualTo(10); - }); + .run(this::testJmsListenerContainerFactoryWithCustomSettings); + } + + private void testJmsListenerContainerFactoryWithCustomSettings( + AssertableApplicationContext loaded) { + DefaultMessageListenerContainer container = getContainer(loaded, + "jmsListenerContainerFactory"); + assertThat(container.isAutoStartup()).isFalse(); + assertThat(container.getSessionAcknowledgeMode()) + .isEqualTo(Session.CLIENT_ACKNOWLEDGE); + assertThat(container.getConcurrentConsumers()).isEqualTo(2); + assertThat(container.getMaxConcurrentConsumers()); } @Test public void testDefaultContainerFactoryWithJtaTransactionManager() { - this.contextLoader.config(TestConfiguration7.class, EnableJmsConfiguration.class) - .load(context -> { - JmsListenerContainerFactory jmsListenerContainerFactory = context - .getBean("jmsListenerContainerFactory", - JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); - DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.isSessionTransacted()).isFalse(); - assertThat(new DirectFieldAccessor(listenerContainer) + this.context.withUserConfiguration(TestConfiguration7.class, + EnableJmsConfiguration.class).run((loaded) -> { + DefaultMessageListenerContainer container = getContainer(loaded, + "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isFalse(); + assertThat(new DirectFieldAccessor(container) .getPropertyValue("transactionManager")).isSameAs( - context.getBean(JtaTransactionManager.class)); + loaded.getBean(JtaTransactionManager.class)); }); } @Test public void testDefaultContainerFactoryNonJtaTransactionManager() { - this.contextLoader.config(TestConfiguration8.class, EnableJmsConfiguration.class) - .load(context -> { - JmsListenerContainerFactory jmsListenerContainerFactory = context - .getBean("jmsListenerContainerFactory", - JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); - DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.isSessionTransacted()).isTrue(); - assertThat(new DirectFieldAccessor(listenerContainer) + this.context.withUserConfiguration(TestConfiguration8.class, + EnableJmsConfiguration.class).run((loaded) -> { + DefaultMessageListenerContainer container = getContainer(loaded, + "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isTrue(); + assertThat(new DirectFieldAccessor(container) .getPropertyValue("transactionManager")).isNull(); }); } @Test public void testDefaultContainerFactoryNoTransactionManager() { - this.contextLoader.config(EnableJmsConfiguration.class).load(context -> { - JmsListenerContainerFactory jmsListenerContainerFactory = context.getBean( - "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); - DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.isSessionTransacted()).isTrue(); - assertThat(new DirectFieldAccessor(listenerContainer) + this.context.withUserConfiguration(EnableJmsConfiguration.class).run((loaded) -> { + DefaultMessageListenerContainer container = getContainer(loaded, + "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isTrue(); + assertThat(new DirectFieldAccessor(container) .getPropertyValue("transactionManager")).isNull(); }); } @Test public void testDefaultContainerFactoryWithMessageConverters() { - this.contextLoader.config(MessageConvertersConfiguration.class, - EnableJmsConfiguration.class).load(context -> { - JmsListenerContainerFactory jmsListenerContainerFactory = context - .getBean("jmsListenerContainerFactory", - JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory.getClass()) - .isEqualTo(DefaultJmsListenerContainerFactory.class); - DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); + this.context.withUserConfiguration(MessageConvertersConfiguration.class, + EnableJmsConfiguration.class).run((loaded) -> { + DefaultMessageListenerContainer container = getContainer(loaded, + "jmsListenerContainerFactory"); + assertThat(container.getMessageConverter()) + .isSameAs(loaded.getBean("myMessageConverter")); }); } @Test public void testCustomContainerFactoryWithConfigurer() { - this.contextLoader.config(TestConfiguration9.class, EnableJmsConfiguration.class) - .env("spring.jms.listener.autoStartup=false").load(context -> { - assertThat(context.containsBean("jmsListenerContainerFactory")) - .isTrue(); - JmsListenerContainerFactory jmsListenerContainerFactory = context - .getBean("customListenerContainerFactory", - JmsListenerContainerFactory.class); - assertThat(jmsListenerContainerFactory) - .isInstanceOf(DefaultJmsListenerContainerFactory.class); - DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(listenerContainer.getCacheLevel()) + this.context + .withUserConfiguration(TestConfiguration9.class, + EnableJmsConfiguration.class) + .withPropertyValues("spring.jms.listener.autoStartup=false") + .run((loaded) -> { + DefaultMessageListenerContainer container = getContainer(loaded, + "customListenerContainerFactory"); + assertThat(container.getCacheLevel()) .isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); - assertThat(listenerContainer.isAutoStartup()).isFalse(); + assertThat(container.isAutoStartup()).isFalse(); }); } + private DefaultMessageListenerContainer getContainer( + AssertableApplicationContext loaded, String name) { + JmsListenerContainerFactory factory = loaded.getBean(name, + JmsListenerContainerFactory.class); + assertThat(factory).isInstanceOf(DefaultJmsListenerContainerFactory.class); + return ((DefaultJmsListenerContainerFactory) factory) + .createListenerContainer(mock(JmsListenerEndpoint.class)); + } + @Test public void testJmsTemplateWithMessageConverter() { - this.contextLoader.config(MessageConvertersConfiguration.class).load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); - }); + this.context.withUserConfiguration(MessageConvertersConfiguration.class) + .run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + assertThat(jmsTemplate.getMessageConverter()) + .isSameAs(loaded.getBean("myMessageConverter")); + }); } @Test public void testJmsTemplateWithDestinationResolver() { - this.contextLoader.config(DestinationResolversConfiguration.class) - .load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getDestinationResolver()) - .isSameAs(context.getBean("myDestinationResolver")); - }); + this.context.withUserConfiguration(DestinationResolversConfiguration.class) + .run((loaded) -> assertThat( + loaded.getBean(JmsTemplate.class).getDestinationResolver()) + .isSameAs(loaded.getBean("myDestinationResolver"))); } @Test public void testJmsTemplateFullCustomization() { - this.contextLoader.config(MessageConvertersConfiguration.class) - .env("spring.jms.template.default-destination=testQueue", + this.context.withUserConfiguration(MessageConvertersConfiguration.class) + .withPropertyValues("spring.jms.template.default-destination=testQueue", "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", "spring.jms.template.priority=6", "spring.jms.template.time-to-live=6000", "spring.jms.template.receive-timeout=2000") - .load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + .run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); assertThat(jmsTemplate.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); + .isSameAs(loaded.getBean("myMessageConverter")); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); assertThat(jmsTemplate.getDefaultDestinationName()) .isEqualTo("testQueue"); @@ -298,26 +284,24 @@ public class JmsAutoConfigurationTests { @Test public void testPubSubDisabledByDefault() { - this.contextLoader.config(TestConfiguration.class).load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - }); + this.context.withUserConfiguration(TestConfiguration.class).run( + (loaded) -> assertThat(loaded.getBean(JmsTemplate.class).isPubSubDomain()) + .isFalse()); } @Test public void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { - this.contextLoader.config(TestConfiguration4.class).load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.isPubSubDomain()).isTrue(); - }); + this.context.withUserConfiguration(TestConfiguration4.class).run( + (loaded) -> assertThat(loaded.getBean(JmsTemplate.class).isPubSubDomain()) + .isTrue()); } @Test public void testPubSubDomainActive() { - this.contextLoader.config(TestConfiguration.class) - .env("spring.jms.pubSubDomain:true").load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - DefaultMessageListenerContainer defaultMessageListenerContainer = context + this.context.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.jms.pubSubDomain:true").run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + DefaultMessageListenerContainer defaultMessageListenerContainer = loaded .getBean(DefaultJmsListenerContainerFactory.class) .createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(jmsTemplate.isPubSubDomain()).isTrue(); @@ -327,29 +311,27 @@ public class JmsAutoConfigurationTests { @Test public void testPubSubDomainOverride() { - this.contextLoader.config(TestConfiguration.class) - .env("spring.jms.pubSubDomain:false").load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = context + this.context.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.jms.pubSubDomain:false").run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(connectionFactory).isNotNull(); - assertThat(connectionFactory) + assertThat(factory).isNotNull() .isEqualTo(jmsTemplate.getConnectionFactory()); }); } @Test public void testActiveMQOverriddenStandalone() { - this.contextLoader.config(TestConfiguration.class) - .env("spring.activemq.inMemory:false").load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = context + this.context.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.activemq.inMemory:false").run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); - assertThat(connectionFactory).isNotNull(); - assertThat(connectionFactory) + assertThat(factory).isNotNull() .isEqualTo(jmsTemplate.getConnectionFactory()); assertThat(((ActiveMQConnectionFactory) jmsTemplate .getConnectionFactory()).getBrokerURL()) @@ -359,16 +341,15 @@ public class JmsAutoConfigurationTests { @Test public void testActiveMQOverriddenRemoteHost() { - this.contextLoader.config(TestConfiguration.class) - .env("spring.activemq.brokerUrl:tcp://remote-host:10000") - .load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = context + this.context.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.activemq.brokerUrl:tcp://remote-host:10000") + .run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); - assertThat(connectionFactory).isNotNull(); - assertThat(connectionFactory) - .isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(factory).isNotNull(); + assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); assertThat(((ActiveMQConnectionFactory) jmsTemplate .getConnectionFactory()).getBrokerURL()) .isEqualTo("tcp://remote-host:10000"); @@ -377,10 +358,10 @@ public class JmsAutoConfigurationTests { @Test public void testActiveMQOverriddenPool() { - this.contextLoader.config(TestConfiguration.class) - .env("spring.activemq.pool.enabled:true").load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - PooledConnectionFactory pool = context + this.context.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.activemq.pool.enabled:true").run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + PooledConnectionFactory pool = loaded .getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); @@ -393,12 +374,12 @@ public class JmsAutoConfigurationTests { @Test public void testActiveMQOverriddenPoolAndStandalone() { - this.contextLoader.config(TestConfiguration.class) - .env("spring.activemq.pool.enabled:true", + this.context.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.inMemory:false") - .load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - PooledConnectionFactory pool = context + .run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + PooledConnectionFactory pool = loaded .getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); @@ -411,12 +392,12 @@ public class JmsAutoConfigurationTests { @Test public void testActiveMQOverriddenPoolAndRemoteServer() { - this.contextLoader.config(TestConfiguration.class) - .env("spring.activemq.pool.enabled:true", + this.context.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.brokerUrl:tcp://remote-host:10000") - .load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - PooledConnectionFactory pool = context + .run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + PooledConnectionFactory pool = loaded .getBean(PooledConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(pool).isNotNull(); @@ -430,12 +411,14 @@ public class JmsAutoConfigurationTests { @Test public void enableJmsAutomatically() throws Exception { - this.contextLoader.config(NoEnableJmsConfiguration.class).load(context -> { - context.getBean( - JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); - context.getBean( - JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); - }); + this.context.withUserConfiguration(NoEnableJmsConfiguration.class) + .run((loaded) -> { + assertThat(loaded) + .hasBean( + JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + .hasBean( + JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); + }); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java index 97982b70f1a..a66baef92c4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java @@ -23,8 +23,9 @@ import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.pool.PooledConnectionFactory; import org.junit.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.test.context.ApplicationContextTester; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -41,67 +42,59 @@ import static org.mockito.Mockito.mockingDetails; */ public class ActiveMQAutoConfigurationTests { - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, + JmsAutoConfiguration.class)); @Test public void brokerIsEmbeddedByDefault() { - this.contextLoader.config(EmptyConfiguration.class).load(context -> { - ConnectionFactory connectionFactory = context - .getBean(ConnectionFactory.class); - assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); - String brokerUrl = ((ActiveMQConnectionFactory) connectionFactory) - .getBrokerURL(); - assertThat(brokerUrl).isEqualTo("vm://localhost?broker.persistent=false"); + this.context.withUserConfiguration(EmptyConfiguration.class).run((loaded) -> { + assertThat(loaded).getBean(ConnectionFactory.class) + .isInstanceOf(ActiveMQConnectionFactory.class); + assertThat(loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) + .isEqualTo("vm://localhost?broker.persistent=false"); }); } @Test public void configurationBacksOffWhenCustomConnectionFactoryExists() { - this.contextLoader.config(CustomConnectionFactoryConfiguration.class) - .load(context -> assertThat( - mockingDetails(context.getBean(ConnectionFactory.class)).isMock()) + this.context.withUserConfiguration(CustomConnectionFactoryConfiguration.class) + .run((loaded) -> assertThat( + mockingDetails(loaded.getBean(ConnectionFactory.class)).isMock()) .isTrue()); } @Test public void customPooledConnectionFactoryConfiguration() { - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.activemq.pool.enabled:true", + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.activemq.pool.enabled:true", "spring.activemq.pool.maxConnections:256", "spring.activemq.pool.idleTimeout:512", "spring.activemq.pool.expiryTimeout:4096", "spring.activemq.pool.configuration.maximumActiveSessionPerConnection:1024", "spring.activemq.pool.configuration.timeBetweenExpirationCheckMillis:2048") - .load(context -> { - ConnectionFactory connectionFactory = context - .getBean(ConnectionFactory.class); - assertThat(connectionFactory) - .isInstanceOf(PooledConnectionFactory.class); - PooledConnectionFactory pooledConnectionFactory = (PooledConnectionFactory) connectionFactory; - assertThat(pooledConnectionFactory.getMaxConnections()) - .isEqualTo(256); - assertThat(pooledConnectionFactory.getIdleTimeout()).isEqualTo(512); - assertThat(pooledConnectionFactory - .getMaximumActiveSessionPerConnection()).isEqualTo(1024); - assertThat( - pooledConnectionFactory.getTimeBetweenExpirationCheckMillis()) - .isEqualTo(2048); - assertThat(pooledConnectionFactory.getExpiryTimeout()) - .isEqualTo(4096); + .run((loaded) -> { + ConnectionFactory factory = loaded.getBean(ConnectionFactory.class); + assertThat(factory).isInstanceOf(PooledConnectionFactory.class); + PooledConnectionFactory pooledFactory = (PooledConnectionFactory) factory; + assertThat(pooledFactory.getMaxConnections()).isEqualTo(256); + assertThat(pooledFactory.getIdleTimeout()).isEqualTo(512); + assertThat(pooledFactory.getMaximumActiveSessionPerConnection()) + .isEqualTo(1024); + assertThat(pooledFactory.getTimeBetweenExpirationCheckMillis()) + .isEqualTo(2048); + assertThat(pooledFactory.getExpiryTimeout()).isEqualTo(4096); }); } @Test public void pooledConnectionFactoryConfiguration() throws JMSException { - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.activemq.pool.enabled:true").load(context -> { - ConnectionFactory connectionFactory = context - .getBean(ConnectionFactory.class); - assertThat(connectionFactory) - .isInstanceOf(PooledConnectionFactory.class); - context.close(); - assertThat(connectionFactory.createConnection()).isNull(); + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.activemq.pool.enabled:true").run((loaded) -> { + ConnectionFactory factory = loaded.getBean(ConnectionFactory.class); + assertThat(factory).isInstanceOf(PooledConnectionFactory.class); + loaded.getSourceApplicationContext().close(); + assertThat(factory.createConnection()).isNull(); }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index 99aea2468a7..6dd9aa32bf8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -41,13 +41,13 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.test.context.ApplicationContextTester; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; import org.springframework.jms.core.SessionCallback; import org.springframework.jms.support.destination.DestinationResolver; import org.springframework.jms.support.destination.DynamicDestinationResolver; @@ -65,110 +65,108 @@ public class ArtemisAutoConfigurationTests { @Rule public final TemporaryFolder folder = new TemporaryFolder(); - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, + JmsAutoConfiguration.class)); @Test public void nativeConnectionFactory() { - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.mode:native").load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = context + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode:native").run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); - assertThat(connectionFactory) - .isEqualTo(jmsTemplate.getConnectionFactory()); - assertNettyConnectionFactory(connectionFactory, "localhost", 61616); - assertThat(connectionFactory.getUser()).isNull(); - assertThat(connectionFactory.getPassword()).isNull(); + assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertNettyConnectionFactory(factory, "localhost", 61616); + assertThat(factory.getUser()).isNull(); + assertThat(factory.getPassword()).isNull(); }); } @Test public void nativeConnectionFactoryCustomHost() { - this.contextLoader - .config(EmptyConfiguration.class).env("spring.artemis.mode:native", + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.host:192.168.1.144", "spring.artemis.port:9876") - .load(context -> { - ActiveMQConnectionFactory connectionFactory = context + .run((loaded) -> { + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); - assertNettyConnectionFactory(connectionFactory, "192.168.1.144", - 9876); + assertNettyConnectionFactory(factory, "192.168.1.144", 9876); }); } @Test public void nativeConnectionFactoryCredentials() { - this.contextLoader - .config(EmptyConfiguration.class).env("spring.artemis.mode:native", + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.user:user", "spring.artemis.password:secret") - .load(context -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory connectionFactory = context + .run((loaded) -> { + JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class); + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); - assertThat(connectionFactory) - .isEqualTo(jmsTemplate.getConnectionFactory()); - assertNettyConnectionFactory(connectionFactory, "localhost", 61616); - assertThat(connectionFactory.getUser()).isEqualTo("user"); - assertThat(connectionFactory.getPassword()).isEqualTo("secret"); + assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertNettyConnectionFactory(factory, "localhost", 61616); + assertThat(factory.getUser()).isEqualTo("user"); + assertThat(factory.getPassword()).isEqualTo("secret"); }); } @Test public void embeddedConnectionFactory() { - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.mode:embedded").load(context -> { - ArtemisProperties properties = context + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode:embedded").run((loaded) -> { + ArtemisProperties properties = loaded .getBean(ArtemisProperties.class); assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); - assertThat(context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); - org.apache.activemq.artemis.core.config.Configuration configuration = context + assertThat(loaded).hasSingleBean(EmbeddedJMS.class); + org.apache.activemq.artemis.core.config.Configuration configuration = loaded .getBean( org.apache.activemq.artemis.core.config.Configuration.class); assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse(); - ActiveMQConnectionFactory connectionFactory = context + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); - assertInVmConnectionFactory(connectionFactory); + assertInVmConnectionFactory(factory); }); } @Test public void embeddedConnectionFactoryByDefault() { // No mode is specified - this.contextLoader.config(EmptyConfiguration.class).load(context -> { - assertThat(context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); - org.apache.activemq.artemis.core.config.Configuration configuration = context + this.context.withUserConfiguration(EmptyConfiguration.class).run((loaded) -> { + assertThat(loaded).hasSingleBean(EmbeddedJMS.class); + org.apache.activemq.artemis.core.config.Configuration configuration = loaded .getBean(org.apache.activemq.artemis.core.config.Configuration.class); assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse(); - - ActiveMQConnectionFactory connectionFactory = context + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); - assertInVmConnectionFactory(connectionFactory); + assertInVmConnectionFactory(factory); }); } @Test public void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { // No mode is specified - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.embedded.enabled:false").load(context -> { - assertThat(context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); - ActiveMQConnectionFactory connectionFactory = context + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.embedded.enabled:false") + .run((loaded) -> { + assertThat(loaded).doesNotHaveBean(EmbeddedJMS.class); + ActiveMQConnectionFactory factory = loaded .getBean(ActiveMQConnectionFactory.class); - assertNettyConnectionFactory(connectionFactory, "localhost", 61616); + assertNettyConnectionFactory(factory, "localhost", 61616); }); } @Test public void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { // No mode is specified - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.mode:embedded", + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false") - .load(context -> { - assertThat(context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); - ActiveMQConnectionFactory connectionFactory = context + .run((loaded) -> { + assertThat(loaded.getBeansOfType(EmbeddedJMS.class)).isEmpty(); + ActiveMQConnectionFactory connectionFactory = loaded .getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(connectionFactory); }); @@ -176,11 +174,11 @@ public class ArtemisAutoConfigurationTests { @Test public void embeddedServerWithDestinations() { - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.embedded.queues=Queue1,Queue2", + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2", "spring.artemis.embedded.topics=Topic1") - .load(context -> { - DestinationChecker checker = new DestinationChecker(context); + .run((loaded) -> { + DestinationChecker checker = new DestinationChecker(loaded); checker.checkQueue("Queue1", true); checker.checkQueue("Queue2", true); checker.checkQueue("QueueWillNotBeAutoCreated", true); @@ -191,19 +189,21 @@ public class ArtemisAutoConfigurationTests { @Test public void embeddedServerWithDestinationConfig() { - this.contextLoader.config(DestinationConfiguration.class).load(context -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("sampleQueue", true); - checker.checkTopic("sampleTopic", true); - }); + this.context.withUserConfiguration(DestinationConfiguration.class) + .run((loaded) -> { + DestinationChecker checker = new DestinationChecker(loaded); + checker.checkQueue("sampleQueue", true); + checker.checkTopic("sampleTopic", true); + }); } @Test public void embeddedServiceWithCustomJmsConfiguration() { // Ignored with custom config - this.contextLoader.config(CustomJmsConfiguration.class) - .env("spring.artemis.embedded.queues=Queue1,Queue2").load(context -> { - DestinationChecker checker = new DestinationChecker(context); + this.context.withUserConfiguration(CustomJmsConfiguration.class) + .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2") + .run((loaded) -> { + DestinationChecker checker = new DestinationChecker(loaded); checker.checkQueue("custom", true); // See CustomJmsConfiguration checker.checkQueue("Queue1", true); checker.checkQueue("Queue2", true); @@ -212,94 +212,77 @@ public class ArtemisAutoConfigurationTests { @Test public void embeddedServiceWithCustomArtemisConfiguration() { - this.contextLoader.config(CustomArtemisConfiguration.class).load(context -> { - org.apache.activemq.artemis.core.config.Configuration configuration = context - .getBean(org.apache.activemq.artemis.core.config.Configuration.class); - assertThat(configuration.getName()).isEqualTo("customFooBar"); - }); + this.context.withUserConfiguration(CustomArtemisConfiguration.class) + .run((loaded) -> assertThat(loaded + .getBean( + org.apache.activemq.artemis.core.config.Configuration.class) + .getName()).isEqualTo("customFooBar")); } @Test public void embeddedWithPersistentMode() throws IOException, JMSException { File dataFolder = this.folder.newFolder(); - final String msgId = UUID.randomUUID().toString(); - + final String messageId = UUID.randomUUID().toString(); // Start the server and post a message to some queue - this.contextLoader.config(EmptyConfiguration.class).env( - "spring.artemis.embedded.queues=TestQueue", - "spring.artemis.embedded.persistent:true", - "spring.artemis.embedded.dataDirectory:" + dataFolder.getAbsolutePath()) - .load(context -> { - - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - jmsTemplate.send("TestQueue", new MessageCreator() { - @Override - public Message createMessage(Session session) - throws JMSException { - return session.createTextMessage(msgId); - } - }); - }); - + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.embedded.queues=TestQueue", + "spring.artemis.embedded.persistent:true", + "spring.artemis.embedded.dataDirectory:" + + dataFolder.getAbsolutePath()) + .run((loaded) -> loaded.getBean(JmsTemplate.class).send("TestQueue", + (session) -> session.createTextMessage(messageId))); // Start the server again and check if our message is still here - this.contextLoader.load(context -> { - - JmsTemplate jmsTemplate2 = context.getBean(JmsTemplate.class); + this.context.run((loaded) -> { + JmsTemplate jmsTemplate2 = loaded.getBean(JmsTemplate.class); jmsTemplate2.setReceiveTimeout(1000L); Message message = jmsTemplate2.receive("TestQueue"); assertThat(message).isNotNull(); - assertThat(((TextMessage) message).getText()).isEqualTo(msgId); + assertThat(((TextMessage) message).getText()).isEqualTo(messageId); }); } @Test public void severalEmbeddedBrokers() { - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.embedded.queues=Queue1").load(rootContext -> { - this.contextLoader.env("spring.artemis.embedded.queues=Queue2") - .load(anotherContext -> { - ArtemisProperties properties = rootContext + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.embedded.queues=Queue1") + .run((first) -> { + this.context + .withPropertyValues("spring.artemis.embedded.queues=Queue2") + .run((second) -> { + ArtemisProperties firstProperties = first .getBean(ArtemisProperties.class); - ArtemisProperties anotherProperties = anotherContext + ArtemisProperties secondProperties = second .getBean(ArtemisProperties.class); - assertThat( - properties.getEmbedded().getServerId() < anotherProperties - .getEmbedded().getServerId()).isTrue(); - DestinationChecker checker = new DestinationChecker( - anotherContext); - checker.checkQueue("Queue1", true); - checker.checkQueue("Queue2", true); - DestinationChecker anotherChecker = new DestinationChecker( - anotherContext); - anotherChecker.checkQueue("Queue2", true); - anotherChecker.checkQueue("Queue1", true); + assertThat(firstProperties.getEmbedded().getServerId()) + .isLessThan(secondProperties.getEmbedded().getServerId()); + DestinationChecker firstChecker = new DestinationChecker(first); + firstChecker.checkQueue("Queue1", true); + firstChecker.checkQueue("Queue2", true); + DestinationChecker secondChecker = new DestinationChecker(second); + secondChecker.checkQueue("Queue2", true); + secondChecker.checkQueue("Queue1", true); }); }); } @Test public void connectToASpecificEmbeddedBroker() { - this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.embedded.serverId=93", + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") - .load(context -> { - this.contextLoader.config(EmptyConfiguration.class).env( - "spring.artemis.mode=embedded", - "spring.artemis.embedded.serverId=93", /* - * Connect to the - * "main" broker - */ - "spring.artemis.embedded.enabled=false" /* - * do not start a - * specific one - */) - .load(anotherContext -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("Queue1", true); - - DestinationChecker anotherChecker = new DestinationChecker( - anotherContext); - anotherChecker.checkQueue("Queue1", true); + .run((first) -> { + this.context.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode=embedded", + // Connect to the "main" broker + "spring.artemis.embedded.serverId=93", + // Do not start a specific one + "spring.artemis.embedded.enabled=false") + .run(secondContext -> { + DestinationChecker firstChecker = new DestinationChecker(first); + firstChecker.checkQueue("Queue1", true); + DestinationChecker secondChecker = new DestinationChecker( + secondContext); + secondChecker.checkQueue("Queue1", true); }); }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java index bc5f5c520e7..6780aac54f7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java @@ -18,8 +18,8 @@ package org.springframework.boot.autoconfigure.web.reactive; import org.junit.Test; -import org.springframework.boot.test.context.ContextLoader; -import org.springframework.boot.test.context.ReactiveWebContextLoader; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.ReactiveWebApplicationContextTester; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.server.reactive.HttpHandler; @@ -39,23 +39,25 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class HttpHandlerAutoConfigurationTests { - private final ReactiveWebContextLoader contextLoader = ContextLoader.reactiveWeb() - .autoConfig(HttpHandlerAutoConfiguration.class); + private final ReactiveWebApplicationContextTester context = new ReactiveWebApplicationContextTester() + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class)); @Test public void shouldNotProcessIfExistingHttpHandler() { - this.contextLoader.config(CustomHttpHandler.class).load(context -> { - assertThat(context.getBeansOfType(HttpHandler.class)).hasSize(1); - assertThat(context.getBean(HttpHandler.class)) - .isSameAs(context.getBean("customHttpHandler")); + this.context.withUserConfiguration(CustomHttpHandler.class).run((loaded) -> { + assertThat(loaded).hasSingleBean(HttpHandler.class); + assertThat(loaded).getBean(HttpHandler.class) + .isSameAs(loaded.getBean("customHttpHandler")); }); } @Test public void shouldConfigureHttpHandlerAnnotation() { - this.contextLoader.autoConfig(WebFluxAutoConfiguration.class).load(context -> { - assertThat(context.getBeansOfType(HttpHandler.class).size()).isEqualTo(1); - }); + this.context + .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) + .run((loaded) -> { + assertThat(loaded).hasSingleBean(HttpHandler.class); + }); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java index 66d71c4c457..32244f65db8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java @@ -30,6 +30,7 @@ import javax.validation.ValidatorFactory; import org.joda.time.DateTime; import org.junit.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; @@ -37,8 +38,9 @@ import org.springframework.boot.autoconfigure.validation.ValidationAutoConfigura import org.springframework.boot.autoconfigure.validation.ValidatorAdapter; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WelcomePageHandlerMapping; -import org.springframework.boot.test.context.ContextLoader; -import org.springframework.boot.test.context.ServletWebContextLoader; +import org.springframework.boot.test.context.AssertableWebApplicationContext; +import org.springframework.boot.test.context.ContextConsumer; +import org.springframework.boot.test.context.WebApplicationContextTester; import org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor; import org.springframework.boot.web.servlet.filter.OrderedHttpPutFormContentFilter; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; @@ -114,124 +116,120 @@ public class WebMvcAutoConfigurationTests { private static final MockServletWebServerFactory webServerFactory = new MockServletWebServerFactory(); - private final ServletWebContextLoader contextLoader = ContextLoader.servletWeb() - .autoConfig(WebMvcAutoConfiguration.class, + private final WebApplicationContextTester context = new WebApplicationContextTester() + .withConfiguration(AutoConfigurations.of(WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class) - .config(Config.class); + PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(Config.class); @Test public void handlerAdaptersCreated() { - this.contextLoader.load(context -> { - assertThat(context.getBeanNamesForType(HandlerAdapter.class).length) - .isEqualTo(3); - assertThat(context.getBean(RequestMappingHandlerAdapter.class) + this.context.run((loaded) -> { + assertThat(loaded).getBeans(HandlerAdapter.class).hasSize(3); + assertThat(loaded.getBean(RequestMappingHandlerAdapter.class) .getMessageConverters()).isNotEmpty().isEqualTo( - context.getBean(HttpMessageConverters.class).getConverters()); + loaded.getBean(HttpMessageConverters.class).getConverters()); }); } @Test public void handlerMappingsCreated() { - this.contextLoader.load(context -> { - assertThat(context.getBeanNamesForType(HandlerMapping.class).length) - .isEqualTo(7); - }); + this.context.run( + (loaded) -> assertThat(loaded).getBeans(HandlerMapping.class).hasSize(7)); } @Test public void resourceHandlerMapping() { - this.contextLoader.load(context -> { - Map> mappingLocations = getResourceMappingLocations( - context); - assertThat(mappingLocations.get("/**")).hasSize(5); - assertThat(mappingLocations.get("/webjars/**")).hasSize(1); - assertThat(mappingLocations.get("/webjars/**").get(0)) + this.context.run((loaded) -> { + Map> locations = getResourceMappingLocations(loaded); + assertThat(locations.get("/**")).hasSize(5); + assertThat(locations.get("/webjars/**")).hasSize(1); + assertThat(locations.get("/webjars/**").get(0)) .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); - assertThat(getResourceResolvers(context, "/webjars/**")).hasSize(1); - assertThat(getResourceTransformers(context, "/webjars/**")).hasSize(0); - assertThat(getResourceResolvers(context, "/**")).hasSize(1); - assertThat(getResourceTransformers(context, "/**")).hasSize(0); + assertThat(getResourceResolvers(loaded, "/webjars/**")).hasSize(1); + assertThat(getResourceTransformers(loaded, "/webjars/**")).hasSize(0); + assertThat(getResourceResolvers(loaded, "/**")).hasSize(1); + assertThat(getResourceTransformers(loaded, "/**")).hasSize(0); }); } @Test public void customResourceHandlerMapping() { - this.contextLoader.env("spring.mvc.static-path-pattern:/static/**") - .load(context -> { - Map> mappingLocations = getResourceMappingLocations( - context); - assertThat(mappingLocations.get("/static/**")).hasSize(5); - assertThat(getResourceResolvers(context, "/static/**")).hasSize(1); + this.context.withPropertyValues("spring.mvc.static-path-pattern:/static/**") + .run((loaded) -> { + Map> locations = getResourceMappingLocations( + loaded); + assertThat(locations.get("/static/**")).hasSize(5); + assertThat(getResourceResolvers(loaded, "/static/**")).hasSize(1); }); } @Test public void resourceHandlerMappingOverrideWebjars() throws Exception { - this.contextLoader.config(WebJars.class).load(context -> { - Map> mappingLocations = getResourceMappingLocations( - context); - assertThat(mappingLocations.get("/webjars/**")).hasSize(1); - assertThat(mappingLocations.get("/webjars/**").get(0)) + this.context.withUserConfiguration(WebJars.class).run((loaded) -> { + Map> locations = getResourceMappingLocations(loaded); + assertThat(locations.get("/webjars/**")).hasSize(1); + assertThat(locations.get("/webjars/**").get(0)) .isEqualTo(new ClassPathResource("/foo/")); }); } @Test public void resourceHandlerMappingOverrideAll() throws Exception { - this.contextLoader.config(AllResources.class).load(context -> { - Map> mappingLocations = getResourceMappingLocations( - context); - assertThat(mappingLocations.get("/**")).hasSize(1); - assertThat(mappingLocations.get("/**").get(0)) + this.context.withUserConfiguration(AllResources.class).run((loaded) -> { + Map> locations = getResourceMappingLocations(loaded); + assertThat(locations.get("/**")).hasSize(1); + assertThat(locations.get("/**").get(0)) .isEqualTo(new ClassPathResource("/foo/")); }); } @Test public void resourceHandlerMappingDisabled() throws Exception { - this.contextLoader.env("spring.resources.add-mappings:false").load(context -> { - Map> mappingLocations = getResourceMappingLocations( - context); - assertThat(mappingLocations.size()).isEqualTo(0); - }); + this.context.withPropertyValues("spring.resources.add-mappings:false") + .run((loaded) -> { + Map> locations = getResourceMappingLocations( + loaded); + assertThat(locations.size()).isEqualTo(0); + }); } @Test public void resourceHandlerChainEnabled() throws Exception { - this.contextLoader.env("spring.resources.chain.enabled:true").load(context -> { - assertThat(getResourceResolvers(context, "/webjars/**")).hasSize(2); - assertThat(getResourceTransformers(context, "/webjars/**")).hasSize(1); - assertThat(getResourceResolvers(context, "/**")) - .extractingResultOf("getClass").containsOnly( - CachingResourceResolver.class, PathResourceResolver.class); - assertThat(getResourceTransformers(context, "/**")) - .extractingResultOf("getClass") - .containsOnly(CachingResourceTransformer.class); - }); + this.context.withPropertyValues("spring.resources.chain.enabled:true") + .run((loaded) -> { + assertThat(getResourceResolvers(loaded, "/webjars/**")).hasSize(2); + assertThat(getResourceTransformers(loaded, "/webjars/**")).hasSize(1); + assertThat(getResourceResolvers(loaded, "/**")) + .extractingResultOf("getClass") + .containsOnly(CachingResourceResolver.class, + PathResourceResolver.class); + assertThat(getResourceTransformers(loaded, "/**")) + .extractingResultOf("getClass") + .containsOnly(CachingResourceTransformer.class); + }); } @Test public void resourceHandlerFixedStrategyEnabled() throws Exception { - this.contextLoader - .env("spring.resources.chain.strategy.fixed.enabled:true", + this.context + .withPropertyValues("spring.resources.chain.strategy.fixed.enabled:true", "spring.resources.chain.strategy.fixed.version:test", "spring.resources.chain.strategy.fixed.paths:/**/*.js") - .load(context -> { - assertThat(getResourceResolvers(context, "/webjars/**")).hasSize(3); - assertThat(getResourceTransformers(context, "/webjars/**")) - .hasSize(2); - assertThat(getResourceResolvers(context, "/**")) + .run((loaded) -> { + assertThat(getResourceResolvers(loaded, "/webjars/**")).hasSize(3); + assertThat(getResourceTransformers(loaded, "/webjars/**")).hasSize(2); + assertThat(getResourceResolvers(loaded, "/**")) .extractingResultOf("getClass") .containsOnly(CachingResourceResolver.class, VersionResourceResolver.class, PathResourceResolver.class); - assertThat(getResourceTransformers(context, "/**")) + assertThat(getResourceTransformers(loaded, "/**")) .extractingResultOf("getClass") .containsOnly(CachingResourceTransformer.class, CssLinkResourceTransformer.class); VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( - context, "/**").get(1); + loaded, "/**").get(1); assertThat(resolver.getStrategyMap().get("/**/*.js")) .isInstanceOf(FixedVersionStrategy.class); }); @@ -239,24 +237,24 @@ public class WebMvcAutoConfigurationTests { @Test public void resourceHandlerContentStrategyEnabled() throws Exception { - this.contextLoader - .env("spring.resources.chain.strategy.content.enabled:true", + this.context + .withPropertyValues( + "spring.resources.chain.strategy.content.enabled:true", "spring.resources.chain.strategy.content.paths:/**,/*.png") - .load(context -> { - assertThat(getResourceResolvers(context, "/webjars/**")).hasSize(3); - assertThat(getResourceTransformers(context, "/webjars/**")) - .hasSize(2); - assertThat(getResourceResolvers(context, "/**")) + .run((loaded) -> { + assertThat(getResourceResolvers(loaded, "/webjars/**")).hasSize(3); + assertThat(getResourceTransformers(loaded, "/webjars/**")).hasSize(2); + assertThat(getResourceResolvers(loaded, "/**")) .extractingResultOf("getClass") .containsOnly(CachingResourceResolver.class, VersionResourceResolver.class, PathResourceResolver.class); - assertThat(getResourceTransformers(context, "/**")) + assertThat(getResourceTransformers(loaded, "/**")) .extractingResultOf("getClass") .containsOnly(CachingResourceTransformer.class, CssLinkResourceTransformer.class); VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( - context, "/**").get(1); + loaded, "/**").get(1); assertThat(resolver.getStrategyMap().get("/*.png")) .isInstanceOf(ContentVersionStrategy.class); }); @@ -264,7 +262,7 @@ public class WebMvcAutoConfigurationTests { @Test public void resourceHandlerChainCustomized() { - this.contextLoader.env("spring.resources.chain.enabled:true", + this.context.withPropertyValues("spring.resources.chain.enabled:true", "spring.resources.chain.cache:false", "spring.resources.chain.strategy.content.enabled:true", "spring.resources.chain.strategy.content.paths:/**,/*.png", @@ -272,60 +270,59 @@ public class WebMvcAutoConfigurationTests { "spring.resources.chain.strategy.fixed.version:test", "spring.resources.chain.strategy.fixed.paths:/**/*.js", "spring.resources.chain.html-application-cache:true", - "spring.resources.chain.gzipped:true"); - this.contextLoader.load(context -> { - assertThat(getResourceResolvers(context, "/webjars/**")).hasSize(3); - assertThat(getResourceTransformers(context, "/webjars/**")).hasSize(2); - assertThat(getResourceResolvers(context, "/**")) - .extractingResultOf("getClass") - .containsOnly(VersionResourceResolver.class, - GzipResourceResolver.class, PathResourceResolver.class); - assertThat(getResourceTransformers(context, "/**")) - .extractingResultOf("getClass") - .containsOnly(CssLinkResourceTransformer.class, - AppCacheManifestTransformer.class); - VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( - context, "/**").get(0); - Map strategyMap = resolver.getStrategyMap(); - assertThat(strategyMap.get("/*.png")) - .isInstanceOf(ContentVersionStrategy.class); - assertThat(strategyMap.get("/**/*.js")) - .isInstanceOf(FixedVersionStrategy.class); - }); + "spring.resources.chain.gzipped:true").run((loaded) -> { + assertThat(getResourceResolvers(loaded, "/webjars/**")).hasSize(3); + assertThat(getResourceTransformers(loaded, "/webjars/**")).hasSize(2); + assertThat(getResourceResolvers(loaded, "/**")) + .extractingResultOf("getClass") + .containsOnly(VersionResourceResolver.class, + GzipResourceResolver.class, + PathResourceResolver.class); + assertThat(getResourceTransformers(loaded, "/**")) + .extractingResultOf("getClass") + .containsOnly(CssLinkResourceTransformer.class, + AppCacheManifestTransformer.class); + VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( + loaded, "/**").get(0); + Map strategyMap = resolver.getStrategyMap(); + assertThat(strategyMap.get("/*.png")) + .isInstanceOf(ContentVersionStrategy.class); + assertThat(strategyMap.get("/**/*.js")) + .isInstanceOf(FixedVersionStrategy.class); + }); } @Test public void noLocaleResolver() throws Exception { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(LocaleResolver.class)).isEmpty(); - }); + this.context.run( + (loaded) -> assertThat(loaded).doesNotHaveBean(LocaleResolver.class)); } @Test public void overrideLocale() throws Exception { - this.contextLoader.env("spring.mvc.locale:en_UK", - "spring.mvc.locale-resolver=fixed"); - this.contextLoader.load(context -> { - // mock request and set user preferred locale - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addPreferredLocale(StringUtils.parseLocaleString("nl_NL")); - request.addHeader(HttpHeaders.ACCEPT_LANGUAGE, "nl_NL"); - LocaleResolver localeResolver = context.getBean(LocaleResolver.class); - assertThat(localeResolver).isInstanceOf(FixedLocaleResolver.class); - Locale locale = localeResolver.resolveLocale(request); - // test locale resolver uses fixed locale and not user preferred locale - assertThat(locale.toString()).isEqualTo("en_UK"); - }); + this.context.withPropertyValues("spring.mvc.locale:en_UK", + "spring.mvc.locale-resolver=fixed").run((loader) -> { + // mock request and set user preferred locale + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addPreferredLocale(StringUtils.parseLocaleString("nl_NL")); + request.addHeader(HttpHeaders.ACCEPT_LANGUAGE, "nl_NL"); + LocaleResolver localeResolver = loader.getBean(LocaleResolver.class); + assertThat(localeResolver).isInstanceOf(FixedLocaleResolver.class); + Locale locale = localeResolver.resolveLocale(request); + // test locale resolver uses fixed locale and not user preferred + // locale + assertThat(locale.toString()).isEqualTo("en_UK"); + }); } @Test public void useAcceptHeaderLocale() { - this.contextLoader.env("spring.mvc.locale:en_UK").load(context -> { + this.context.withPropertyValues("spring.mvc.locale:en_UK").run((loader) -> { // mock request and set user preferred locale MockHttpServletRequest request = new MockHttpServletRequest(); request.addPreferredLocale(StringUtils.parseLocaleString("nl_NL")); request.addHeader(HttpHeaders.ACCEPT_LANGUAGE, "nl_NL"); - LocaleResolver localeResolver = context.getBean(LocaleResolver.class); + LocaleResolver localeResolver = loader.getBean(LocaleResolver.class); assertThat(localeResolver).isInstanceOf(AcceptHeaderLocaleResolver.class); Locale locale = localeResolver.resolveLocale(request); // test locale resolver uses user preferred locale @@ -335,10 +332,10 @@ public class WebMvcAutoConfigurationTests { @Test public void useDefaultLocaleIfAcceptHeaderNoSet() { - this.contextLoader.env("spring.mvc.locale:en_UK").load(context -> { + this.context.withPropertyValues("spring.mvc.locale:en_UK").run((loaded) -> { // mock request and set user preferred locale MockHttpServletRequest request = new MockHttpServletRequest(); - LocaleResolver localeResolver = context.getBean(LocaleResolver.class); + LocaleResolver localeResolver = loaded.getBean(LocaleResolver.class); assertThat(localeResolver).isInstanceOf(AcceptHeaderLocaleResolver.class); Locale locale = localeResolver.resolveLocale(request); // test locale resolver uses default locale if no header is set @@ -348,8 +345,8 @@ public class WebMvcAutoConfigurationTests { @Test public void noDateFormat() { - this.contextLoader.load(context -> { - FormattingConversionService conversionService = context + this.context.run((loaded) -> { + FormattingConversionService conversionService = loaded .getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); // formatting conversion service should use simple toString() @@ -360,480 +357,454 @@ public class WebMvcAutoConfigurationTests { @Test public void overrideDateFormat() { - this.contextLoader.env("spring.mvc.date-format:dd*MM*yyyy").load(context -> { - FormattingConversionService conversionService = context - .getBean(FormattingConversionService.class); - Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); - assertThat(conversionService.convert(date, String.class)) - .isEqualTo("25*06*1988"); - }); + this.context.withPropertyValues("spring.mvc.date-format:dd*MM*yyyy") + .run((loaded) -> { + FormattingConversionService conversionService = loaded + .getBean(FormattingConversionService.class); + Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); + assertThat(conversionService.convert(date, String.class)) + .isEqualTo("25*06*1988"); + }); } @Test public void noMessageCodesResolver() { - this.contextLoader.load(context -> { - assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()).isNull(); - }); + this.context.run((loaded) -> assertThat(loaded + .getBean(WebMvcAutoConfigurationAdapter.class).getMessageCodesResolver()) + .isNull()); } @Test public void overrideMessageCodesFormat() { - this.contextLoader - .env("spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); - this.contextLoader.load(context -> { - assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()).isNotNull(); - }); + this.context + .withPropertyValues( + "spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE") + .run((loaded) -> assertThat( + loaded.getBean(WebMvcAutoConfigurationAdapter.class) + .getMessageCodesResolver()).isNotNull()); } @Test public void ignoreDefaultModelOnRedirectIsTrue() { - this.contextLoader.load(context -> { - RequestMappingHandlerAdapter adapter = context - .getBean(RequestMappingHandlerAdapter.class); - assertThat(adapter).extracting("ignoreDefaultModelOnRedirect") - .containsExactly(true); - }); + this.context.run( + (loaded) -> assertThat(loaded.getBean(RequestMappingHandlerAdapter.class)) + .extracting("ignoreDefaultModelOnRedirect") + .containsExactly(true)); } @Test public void overrideIgnoreDefaultModelOnRedirect() { - this.contextLoader.env("spring.mvc.ignore-default-model-on-redirect:false"); - this.contextLoader.load(context -> { - RequestMappingHandlerAdapter adapter = context - .getBean(RequestMappingHandlerAdapter.class); - assertThat(adapter).extracting("ignoreDefaultModelOnRedirect") - .containsExactly(false); - }); + this.context + .withPropertyValues("spring.mvc.ignore-default-model-on-redirect:false") + .run((loaded) -> assertThat( + loaded.getBean(RequestMappingHandlerAdapter.class)) + .extracting("ignoreDefaultModelOnRedirect") + .containsExactly(false)); } @Test public void customViewResolver() { - this.contextLoader.config(CustomViewResolver.class).load(context -> { - assertThat(context.getBean("viewResolver")) - .isInstanceOf(MyViewResolver.class); - }); + this.context.withUserConfiguration(CustomViewResolver.class) + .run((loaded) -> assertThat(loaded.getBean("viewResolver")) + .isInstanceOf(MyViewResolver.class)); } @Test public void customContentNegotiatingViewResolver() throws Exception { - this.contextLoader.config(CustomContentNegotiatingViewResolver.class); - this.contextLoader.load(context -> { - Map beans = context - .getBeansOfType(ContentNegotiatingViewResolver.class); - assertThat(beans.size()).isEqualTo(1); - assertThat(beans.keySet().iterator().next()).isEqualTo("myViewResolver"); - }); + this.context.withUserConfiguration(CustomContentNegotiatingViewResolver.class) + .run((loaded) -> assertThat(loaded) + .getBeanNames(ContentNegotiatingViewResolver.class) + .containsOnly("myViewResolver")); } @Test public void faviconMapping() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(ResourceHttpRequestHandler.class) - .get("faviconRequestHandler")).isNotNull(); - assertThat(context.getBeansOfType(SimpleUrlHandlerMapping.class) - .get("faviconHandlerMapping")).isNotNull(); - Map> mappingLocations = getFaviconMappingLocations( - context); - assertThat(mappingLocations.get("/**/favicon.ico")).hasSize(6); + this.context.run((loaded) -> { + assertThat(loaded).getBeanNames(ResourceHttpRequestHandler.class) + .contains("faviconRequestHandler"); + assertThat(loaded).getBeans(SimpleUrlHandlerMapping.class) + .containsKey("faviconHandlerMapping"); + assertThat(getFaviconMappingLocations(loaded).get("/**/favicon.ico")) + .hasSize(6); }); } @Test public void faviconMappingUsesStaticLocations() { - this.contextLoader.env("spring.resources.static-locations=classpath:/static"); - this.contextLoader.load(context -> { - assertThat(getFaviconMappingLocations(context).get("/**/favicon.ico")) - .hasSize(2); - }); + this.context + .withPropertyValues("spring.resources.static-locations=classpath:/static") + .run((loaded) -> assertThat( + getFaviconMappingLocations(loaded).get("/**/favicon.ico")) + .hasSize(2)); } @Test public void faviconMappingDisabled() throws IllegalAccessException { - this.contextLoader.env("spring.mvc.favicon.enabled:false").load(context -> { - assertThat(context.getBeansOfType(ResourceHttpRequestHandler.class) - .get("faviconRequestHandler")).isNull(); - assertThat(context.getBeansOfType(SimpleUrlHandlerMapping.class) - .get("faviconHandlerMapping")).isNull(); - }); + this.context.withPropertyValues("spring.mvc.favicon.enabled:false") + .run((loaded) -> { + assertThat(loaded).getBeans(ResourceHttpRequestHandler.class) + .doesNotContainKey("faviconRequestHandler"); + assertThat(loaded).getBeans(SimpleUrlHandlerMapping.class) + .doesNotContainKey("faviconHandlerMapping"); + }); } @Test public void defaultAsyncRequestTimeout() throws Exception { - this.contextLoader.load(context -> { - RequestMappingHandlerAdapter adapter = context - .getBean(RequestMappingHandlerAdapter.class); - assertThat(ReflectionTestUtils.getField(adapter, "asyncRequestTimeout")) - .isNull(); - }); + this.context.run((loaded) -> assertThat(ReflectionTestUtils.getField( + loaded.getBean(RequestMappingHandlerAdapter.class), + "asyncRequestTimeout")).isNull()); } @Test public void customAsyncRequestTimeout() throws Exception { - this.contextLoader.env("spring.mvc.async.request-timeout:12345").load(context -> { - RequestMappingHandlerAdapter adapter = context - .getBean(RequestMappingHandlerAdapter.class); - assertThat(ReflectionTestUtils.getField(adapter, "asyncRequestTimeout")) - .isEqualTo(12345L); - }); + this.context.withPropertyValues("spring.mvc.async.request-timeout:12345") + .run((loaded) -> assertThat(ReflectionTestUtils.getField( + loaded.getBean(RequestMappingHandlerAdapter.class), + "asyncRequestTimeout")).isEqualTo(12345L)); } @Test public void customMediaTypes() throws Exception { - this.contextLoader.env("spring.mvc.mediaTypes.yaml:text/yaml").load(context -> { - RequestMappingHandlerAdapter adapter = context - .getBean(RequestMappingHandlerAdapter.class); - ContentNegotiationManager contentNegotiationManager = (ContentNegotiationManager) ReflectionTestUtils - .getField(adapter, "contentNegotiationManager"); - assertThat(contentNegotiationManager.getAllFileExtensions()).contains("yaml"); - }); + this.context.withPropertyValues("spring.mvc.mediaTypes.yaml:text/yaml") + .run((loaded) -> { + RequestMappingHandlerAdapter adapter = loaded + .getBean(RequestMappingHandlerAdapter.class); + ContentNegotiationManager contentNegotiationManager = (ContentNegotiationManager) ReflectionTestUtils + .getField(adapter, "contentNegotiationManager"); + assertThat(contentNegotiationManager.getAllFileExtensions()) + .contains("yaml"); + }); } @Test public void httpPutFormContentFilterIsAutoConfigured() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) - .hasSize(1); - }); + this.context.run((loaded) -> assertThat(loaded) + .hasSingleBean(OrderedHttpPutFormContentFilter.class)); } @Test public void httpPutFormContentFilterCanBeOverridden() { - this.contextLoader.config(CustomHttpPutFormContentFilter.class).load(context -> { - assertThat(context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) - .hasSize(0); - assertThat(context.getBeansOfType(HttpPutFormContentFilter.class)).hasSize(1); - }); + this.context.withUserConfiguration(CustomHttpPutFormContentFilter.class) + .run((loaded) -> { + assertThat(loaded) + .doesNotHaveBean(OrderedHttpPutFormContentFilter.class); + assertThat(loaded).hasSingleBean(HttpPutFormContentFilter.class); + }); } @Test public void httpPutFormContentFilterCanBeDisabled() throws Exception { - this.contextLoader.env("spring.mvc.formcontent.putfilter.enabled=false"); - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(HttpPutFormContentFilter.class)).isEmpty(); - }); + this.context.withPropertyValues("spring.mvc.formcontent.putfilter.enabled=false") + .run((loaded) -> assertThat(loaded) + .doesNotHaveBean(HttpPutFormContentFilter.class)); } @Test public void customConfigurableWebBindingInitializer() { - this.contextLoader.config(CustomConfigurableWebBindingInitializer.class); - this.contextLoader.load(context -> { - assertThat(context.getBean(RequestMappingHandlerAdapter.class) - .getWebBindingInitializer()) - .isInstanceOf(CustomWebBindingInitializer.class); - }); + this.context.withUserConfiguration(CustomConfigurableWebBindingInitializer.class) + .run((loaded) -> assertThat( + loaded.getBean(RequestMappingHandlerAdapter.class) + .getWebBindingInitializer()) + .isInstanceOf(CustomWebBindingInitializer.class)); } @Test public void customRequestMappingHandlerMapping() { - this.contextLoader.config(CustomRequestMappingHandlerMapping.class); - this.contextLoader.load(context -> { - assertThat(context.getBean(RequestMappingHandlerMapping.class)) - .isInstanceOf(MyRequestMappingHandlerMapping.class); - }); + this.context.withUserConfiguration(CustomRequestMappingHandlerMapping.class) + .run((loaded) -> assertThat(loaded) + .getBean(RequestMappingHandlerMapping.class) + .isInstanceOf(MyRequestMappingHandlerMapping.class)); } @Test public void customRequestMappingHandlerAdapter() { - this.contextLoader.config(CustomRequestMappingHandlerAdapter.class); - this.contextLoader.load(context -> { - assertThat(context.getBean(RequestMappingHandlerAdapter.class)) - .isInstanceOf(MyRequestMappingHandlerAdapter.class); - }); + this.context.withUserConfiguration(CustomRequestMappingHandlerAdapter.class) + .run((loaded) -> assertThat(loaded) + .getBean(RequestMappingHandlerAdapter.class) + .isInstanceOf(MyRequestMappingHandlerAdapter.class)); } @Test public void multipleWebMvcRegistrations() { - this.contextLoader.config(MultipleWebMvcRegistrations.class).load(context -> { - assertThat(context.getBean(RequestMappingHandlerMapping.class)) - .isNotInstanceOf(MyRequestMappingHandlerMapping.class); - assertThat(context.getBean(RequestMappingHandlerAdapter.class)) - .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); - }); + this.context.withUserConfiguration(MultipleWebMvcRegistrations.class) + .run((loaded) -> { + assertThat(loaded.getBean(RequestMappingHandlerMapping.class)) + .isNotInstanceOf(MyRequestMappingHandlerMapping.class); + assertThat(loaded.getBean(RequestMappingHandlerAdapter.class)) + .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); + }); } @Test public void defaultLogResolvedException() { - this.contextLoader.load(context -> { - assertExceptionResolverWarnLoggers(context, - warnLogger -> assertThat(warnLogger).isNull()); - }); + this.context.run(assertExceptionResolverWarnLoggers( + (logger) -> assertThat(logger).isNull())); } @Test public void customLogResolvedException() { - this.contextLoader.env("spring.mvc.log-resolved-exception:true").load(context -> { - assertExceptionResolverWarnLoggers(context, - warnLogger -> assertThat(warnLogger).isNotNull()); - }); + this.context.withPropertyValues("spring.mvc.log-resolved-exception:true") + .run(assertExceptionResolverWarnLoggers( + (logger) -> assertThat(logger).isNotNull())); + } + + private ContextConsumer assertExceptionResolverWarnLoggers( + Consumer consumer) { + return (loaded) -> { + HandlerExceptionResolver resolver = loaded + .getBean(HandlerExceptionResolver.class); + assertThat(resolver).isInstanceOf(HandlerExceptionResolverComposite.class); + List delegates = ((HandlerExceptionResolverComposite) resolver) + .getExceptionResolvers(); + for (HandlerExceptionResolver delegate : delegates) { + if (delegate instanceof AbstractHandlerExceptionResolver) { + consumer.accept(ReflectionTestUtils.getField(delegate, "warnLogger")); + } + } + }; } @Test public void welcomePageMappingProducesNotFoundResponseWhenThereIsNoWelcomePage() { - this.contextLoader - .env("spring.resources.static-locations:classpath:/no-welcome-page/"); - this.contextLoader.loadWeb(context -> { - assertThat(context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); - MockMvcBuilders.webAppContextSetup(context).build() - .perform(get("/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isNotFound()); - }); + this.context + .withPropertyValues( + "spring.resources.static-locations:classpath:/no-welcome-page/") + .run((loaded) -> { + assertThat(loaded).hasSingleBean(WelcomePageHandlerMapping.class); + MockMvcBuilders.webAppContextSetup(loaded).build() + .perform(get("/").accept(MediaType.TEXT_HTML)) + .andExpect(status().isNotFound()); + }); } @Test public void welcomePageRootHandlerIsNotRegisteredWhenStaticPathPatternIsNotSlashStarStar() { - this.contextLoader.env( - "spring.resources.static-locations:classpath:/welcome-page/", - "spring.mvc.static-path-pattern:/foo/**"); - this.contextLoader.load(context -> { - WelcomePageHandlerMapping welcomePageHandlerMapping = context - .getBean(WelcomePageHandlerMapping.class); - assertThat(welcomePageHandlerMapping.getRootHandler()).isNull(); - }); + this.context + .withPropertyValues( + "spring.resources.static-locations:classpath:/welcome-page/", + "spring.mvc.static-path-pattern:/foo/**") + .run((loaded) -> assertThat( + loaded.getBean(WelcomePageHandlerMapping.class).getRootHandler()) + .isNull()); } @Test public void welcomePageMappingHandlesRequestsThatAcceptTextHtml() { - this.contextLoader - .env("spring.resources.static-locations:classpath:/welcome-page/"); - this.contextLoader.loadWeb(context -> { - assertThat(context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); - mockMvc.perform(get("/").accept("*/*")).andExpect(status().isOk()) - .andExpect(forwardedUrl("index.html")); - }); + this.context + .withPropertyValues( + "spring.resources.static-locations:classpath:/welcome-page/") + .run((loaded) -> { + assertThat(loaded).hasSingleBean(WelcomePageHandlerMapping.class); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(loaded).build(); + mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)) + .andExpect(status().isOk()) + .andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/").accept("*/*")).andExpect(status().isOk()) + .andExpect(forwardedUrl("index.html")); + }); } @Test public void welcomePageMappingDoesNotHandleRequestsThatDoNotAcceptTextHtml() { - this.contextLoader - .env("spring.resources.static-locations:classpath:/welcome-page/"); - this.contextLoader.loadWeb(context -> { - assertThat(context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNotFound()); - }); + this.context + .withPropertyValues( + "spring.resources.static-locations:classpath:/welcome-page/") + .run((loaded) -> { + assertThat(loaded).hasSingleBean(WelcomePageHandlerMapping.class); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(loaded).build(); + mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + }); } @Test public void welcomePageMappingHandlesRequestsWithNoAcceptHeader() { - this.contextLoader - .env("spring.resources.static-locations:classpath:/welcome-page/"); - this.contextLoader.loadWeb(context -> { - assertThat(context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(forwardedUrl("index.html")); - }); + this.context + .withPropertyValues( + "spring.resources.static-locations:classpath:/welcome-page/") + .run((loaded) -> { + assertThat(loaded).hasSingleBean(WelcomePageHandlerMapping.class); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(loaded).build(); + mockMvc.perform(get("/")).andExpect(status().isOk()) + .andExpect(forwardedUrl("index.html")); + }); } @Test public void welcomePageMappingHandlesRequestsWithEmptyAcceptHeader() throws Exception { - this.contextLoader - .env("spring.resources.static-locations:classpath:/welcome-page/"); - this.contextLoader.loadWeb(context -> { - assertThat(context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/").header(HttpHeaders.ACCEPT, "")) - .andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); - }); + this.context + .withPropertyValues( + "spring.resources.static-locations:classpath:/welcome-page/") + .run((loaded) -> { + assertThat(loaded).hasSingleBean(WelcomePageHandlerMapping.class); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(loaded).build(); + mockMvc.perform(get("/").header(HttpHeaders.ACCEPT, "")) + .andExpect(status().isOk()) + .andExpect(forwardedUrl("index.html")); + }); } @Test public void welcomePageMappingWorksWithNoTrailingSlashOnResourceLocation() throws Exception { - this.contextLoader - .env("spring.resources.static-locations:classpath:/welcome-page"); - this.contextLoader.loadWeb(context -> { - assertThat(context.getBeansOfType(WelcomePageHandlerMapping.class)) - .hasSize(1); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)) - .andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); - }); + this.context + .withPropertyValues( + "spring.resources.static-locations:classpath:/welcome-page") + .run((loaded) -> { + assertThat(loaded).hasSingleBean(WelcomePageHandlerMapping.class); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(loaded).build(); + mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)) + .andExpect(status().isOk()) + .andExpect(forwardedUrl("index.html")); + }); } @Test public void validatorWhenNoValidatorShouldUseDefault() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - assertThat(context.getBeansOfType(javax.validation.Validator.class)) - .isEmpty(); - String[] springValidatorBeans = context.getBeanNamesForType(Validator.class); - assertThat(springValidatorBeans).containsExactly("mvcValidator"); + this.context.run((loaded) -> { + assertThat(loaded).doesNotHaveBean(ValidatorFactory.class); + assertThat(loaded).doesNotHaveBean(javax.validation.Validator.class); + assertThat(loaded).getBeanNames(Validator.class).containsOnly("mvcValidator"); }); } @Test public void validatorWhenNoCustomizationShouldUseAutoConfigured() { - this.contextLoader.autoConfigFirst(ValidationAutoConfiguration.class); - this.contextLoader.load(context -> { - String[] jsrValidatorBeans = context - .getBeanNamesForType(javax.validation.Validator.class); - String[] springValidatorBeans = context.getBeanNamesForType(Validator.class); - assertThat(jsrValidatorBeans).containsExactly("defaultValidator"); - assertThat(springValidatorBeans).containsExactly("defaultValidator", - "mvcValidator"); - Validator validator = context.getBean("mvcValidator", Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(defaultValidator); - // Primary Spring validator is the one used by MVC behind the scenes - assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); - }); + this.context + .withConfiguration( + AutoConfigurations.of(ValidationAutoConfiguration.class)) + .run((loaded) -> { + assertThat(loaded).getBeanNames(javax.validation.Validator.class) + .containsOnly("defaultValidator"); + assertThat(loaded).getBeanNames(Validator.class) + .containsOnly("defaultValidator", "mvcValidator"); + Validator validator = loaded.getBean("mvcValidator", Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Object defaultValidator = loaded.getBean("defaultValidator"); + assertThat(((ValidatorAdapter) validator).getTarget()) + .isSameAs(defaultValidator); + // Primary Spring validator is the one used by MVC behind the scenes + assertThat(loaded.getBean(Validator.class)) + .isEqualTo(defaultValidator); + }); } @Test public void validatorWithConfigurerShouldUseSpringValidator() { - this.contextLoader.config(MvcValidator.class).load(context -> { - assertThat(context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - assertThat(context.getBeansOfType(javax.validation.Validator.class)) - .isEmpty(); - String[] springValidatorBeans = context.getBeanNamesForType(Validator.class); - assertThat(springValidatorBeans).containsExactly("mvcValidator"); - assertThat(context.getBean("mvcValidator")) - .isSameAs(context.getBean(MvcValidator.class).validator); + this.context.withUserConfiguration(MvcValidator.class).run((loaded) -> { + assertThat(loaded).doesNotHaveBean(ValidatorFactory.class); + assertThat(loaded).doesNotHaveBean(javax.validation.Validator.class); + assertThat(loaded).getBeanNames(Validator.class).containsOnly("mvcValidator"); + assertThat(loaded.getBean("mvcValidator")) + .isSameAs(loaded.getBean(MvcValidator.class).validator); }); } @Test public void validatorWithConfigurerDoesNotExposeJsr303() { - this.contextLoader.config(MvcJsr303Validator.class).load(context -> { - assertThat(context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - assertThat(context.getBeansOfType(javax.validation.Validator.class)) - .isEmpty(); - String[] springValidatorBeans = context.getBeanNamesForType(Validator.class); - assertThat(springValidatorBeans).containsExactly("mvcValidator"); - Validator validator = context.getBean("mvcValidator", Validator.class); + this.context.withUserConfiguration(MvcJsr303Validator.class).run((loaded) -> { + assertThat(loaded).doesNotHaveBean(ValidatorFactory.class); + assertThat(loaded).doesNotHaveBean(javax.validation.Validator.class); + assertThat(loaded).getBeanNames(Validator.class).containsOnly("mvcValidator"); + Validator validator = loaded.getBean("mvcValidator", Validator.class); assertThat(validator).isInstanceOf(ValidatorAdapter.class); assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(context.getBean(MvcJsr303Validator.class).validator); + .isSameAs(loaded.getBean(MvcJsr303Validator.class).validator); }); } @Test public void validatorWithConfigurerTakesPrecedence() { - this.contextLoader.autoConfigFirst(ValidationAutoConfiguration.class) - .config(MvcValidator.class); - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(ValidatorFactory.class)).hasSize(1); - assertThat(context.getBeansOfType(javax.validation.Validator.class)) - .hasSize(1); - String[] springValidatorBeans = context.getBeanNamesForType(Validator.class); - assertThat(springValidatorBeans).containsExactly("defaultValidator", - "mvcValidator"); - assertThat(context.getBean("mvcValidator")) - .isSameAs(context.getBean(MvcValidator.class).validator); - // Primary Spring validator is the auto-configured one as the MVC one has been - // customized via a WebMvcConfigurer - assertThat(context.getBean(Validator.class)) - .isEqualTo(context.getBean("defaultValidator")); - }); - + this.context + .withConfiguration( + AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withUserConfiguration(MvcValidator.class).run((loaded) -> { + assertThat(loaded).hasSingleBean(ValidatorFactory.class); + assertThat(loaded).hasSingleBean(javax.validation.Validator.class); + assertThat(loaded).getBeanNames(Validator.class) + .containsOnly("defaultValidator", "mvcValidator"); + assertThat(loaded.getBean("mvcValidator")) + .isSameAs(loaded.getBean(MvcValidator.class).validator); + // Primary Spring validator is the auto-configured one as the MVC one + // has been customized via a WebMvcConfigurer + assertThat(loaded.getBean(Validator.class)) + .isEqualTo(loaded.getBean("defaultValidator")); + }); } @Test public void validatorWithCustomSpringValidatorIgnored() { - this.contextLoader.autoConfigFirst(ValidationAutoConfiguration.class) - .config(CustomSpringValidator.class); - this.contextLoader.load(context -> { - String[] jsrValidatorBeans = context - .getBeanNamesForType(javax.validation.Validator.class); - String[] springValidatorBeans = context.getBeanNamesForType(Validator.class); - assertThat(jsrValidatorBeans).containsExactly("defaultValidator"); - assertThat(springValidatorBeans).containsExactly("customSpringValidator", - "defaultValidator", "mvcValidator"); - Validator validator = context.getBean("mvcValidator", Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(defaultValidator); - // Primary Spring validator is the one used by MVC behind the scenes - assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); - }); - + this.context + .withConfiguration( + AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withUserConfiguration(CustomSpringValidator.class).run((loaded) -> { + assertThat(loaded).getBeanNames(javax.validation.Validator.class) + .containsOnly("defaultValidator"); + assertThat(loaded).getBeanNames(Validator.class).containsOnly( + "customSpringValidator", "defaultValidator", "mvcValidator"); + Validator validator = loaded.getBean("mvcValidator", Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Object defaultValidator = loaded.getBean("defaultValidator"); + assertThat(((ValidatorAdapter) validator).getTarget()) + .isSameAs(defaultValidator); + // Primary Spring validator is the one used by MVC behind the scenes + assertThat(loaded.getBean(Validator.class)) + .isEqualTo(defaultValidator); + }); } @Test public void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { - this.contextLoader.autoConfigFirst(ValidationAutoConfiguration.class) - .config(CustomJsr303Validator.class); - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(ValidatorFactory.class)).isEmpty(); - String[] jsrValidatorBeans = context - .getBeanNamesForType(javax.validation.Validator.class); - String[] springValidatorBeans = context.getBeanNamesForType(Validator.class); - assertThat(jsrValidatorBeans).containsExactly("customJsr303Validator"); - assertThat(springValidatorBeans).containsExactly("mvcValidator"); - Validator validator = context.getBean(Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Validator target = ((ValidatorAdapter) validator).getTarget(); - assertThat(ReflectionTestUtils.getField(target, "targetValidator")) - .isSameAs(context.getBean("customJsr303Validator")); - }); + this.context + .withConfiguration( + AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withUserConfiguration(CustomJsr303Validator.class).run((loaded) -> { + assertThat(loaded).doesNotHaveBean(ValidatorFactory.class); + assertThat(loaded).getBeanNames(javax.validation.Validator.class) + .containsOnly("customJsr303Validator"); + assertThat(loaded).getBeanNames(Validator.class) + .containsOnly("mvcValidator"); + Validator validator = loaded.getBean(Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Validator target = ((ValidatorAdapter) validator).getTarget(); + assertThat(ReflectionTestUtils.getField(target, "targetValidator")) + .isSameAs(loaded.getBean("customJsr303Validator")); + }); } @Test public void httpMessageConverterThatUsesConversionServiceDoesNotCreateACycle() { - // TODO load(ContextConsumer...) or load() - this.contextLoader.config(CustomHttpMessageConverter.class).load(context -> { - }); - } - - private void assertExceptionResolverWarnLoggers(ApplicationContext context, - Consumer warnLogger) { - HandlerExceptionResolver exceptionResolver = context - .getBean(HandlerExceptionResolver.class); - assertThat(exceptionResolver) - .isInstanceOf(HandlerExceptionResolverComposite.class); - List delegates = ((HandlerExceptionResolverComposite) exceptionResolver) - .getExceptionResolvers(); - for (HandlerExceptionResolver delegate : delegates) { - if (delegate instanceof AbstractHandlerExceptionResolver) { - warnLogger.accept(ReflectionTestUtils.getField(delegate, "warnLogger")); - } - } + this.context.withUserConfiguration(CustomHttpMessageConverter.class) + .run((loaded) -> assertThat(loaded).hasNotFailed()); } protected Map> getFaviconMappingLocations( ApplicationContext context) { - HandlerMapping mapping = (HandlerMapping) context - .getBean("faviconHandlerMapping"); - return getMappingLocations(mapping); + return getMappingLocations( + context.getBean("faviconHandlerMapping", HandlerMapping.class)); } protected Map> getResourceMappingLocations( ApplicationContext context) throws IllegalAccessException { - HandlerMapping mapping = (HandlerMapping) context - .getBean("resourceHandlerMapping"); - return getMappingLocations(mapping); + return getMappingLocations( + context.getBean("resourceHandlerMapping", HandlerMapping.class)); } protected List getResourceResolvers(ApplicationContext context, String mapping) { - SimpleUrlHandlerMapping handler = (SimpleUrlHandlerMapping) context - .getBean("resourceHandlerMapping"); - ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler + ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) context + .getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class) .getHandlerMap().get(mapping); return resourceHandler.getResourceResolvers(); } protected List getResourceTransformers( ApplicationContext context, String mapping) { - SimpleUrlHandlerMapping handler = (SimpleUrlHandlerMapping) context - .getBean("resourceHandlerMapping"); + SimpleUrlHandlerMapping handler = context.getBean("resourceHandlerMapping", + SimpleUrlHandlerMapping.class); ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler .getHandlerMap().get(mapping); return resourceHandler.getResourceTransformers(); @@ -844,8 +815,8 @@ public class WebMvcAutoConfigurationTests { Map> mappingLocations = new LinkedHashMap<>(); if (mapping instanceof SimpleUrlHandlerMapping) { ((SimpleUrlHandlerMapping) mapping).getHandlerMap().forEach((key, value) -> { - mappingLocations.put(key, (List) ReflectionTestUtils - .getField(value, "locations")); + Object locations = ReflectionTestUtils.getField(value, "locations"); + mappingLocations.put(key, (List) locations); }); } return mappingLocations; @@ -864,6 +835,7 @@ public class WebMvcAutoConfigurationTests { throws Exception { response.getOutputStream().write("Hello World".getBytes()); } + }; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java index c1cd76bde88..50356f5fcf7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java @@ -16,14 +16,17 @@ package org.springframework.boot.autoconfigure.webservices; +import java.util.Collection; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.boot.test.context.ContextLoader; -import org.springframework.boot.test.context.ServletWebContextLoader; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.WebApplicationContextTester; import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.ApplicationContext; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -37,52 +40,46 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class WebServicesAutoConfigurationTests { - private final ServletWebContextLoader contextLoader = ContextLoader.servletWeb() - .autoConfig(WebServicesAutoConfiguration.class); + private final WebApplicationContextTester context = new WebApplicationContextTester() + .withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class)); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void defaultConfiguration() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - }); + this.context.run((loaded) -> assertThat(loaded) + .hasSingleBean(ServletRegistrationBean.class)); } @Test public void customPathMustBeginWithASlash() { - this.contextLoader.env("spring.webservices.path=invalid") - .loadAndFail(BeanCreationException.class, (ex) -> { - System.out.println(ex.getMessage()); - assertThat(ex.getMessage()).contains( - "Failed to bind properties under 'spring.webservices'"); + this.context.withPropertyValues("spring.webservices.path=invalid") + .run((loaded) -> { + assertThat(loaded).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining( + "Failed to bind properties under 'spring.webservices'"); }); } @Test public void customPath() { - this.contextLoader.env("spring.webservices.path=/valid").load(context -> { - ServletRegistrationBean servletRegistrationBean = context - .getBean(ServletRegistrationBean.class); - assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*"); - }); + this.context.withPropertyValues("spring.webservices.path=/valid") + .run((loaded) -> assertThat(getUrlMappings(loaded)).contains("/valid/*")); } @Test public void customPathWithTrailingSlash() { - this.contextLoader.env("spring.webservices.path=/valid/").load(context -> { - ServletRegistrationBean servletRegistrationBean = context - .getBean(ServletRegistrationBean.class); - assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*"); - }); + this.context.withPropertyValues("spring.webservices.path=/valid/") + .run((loaded) -> assertThat(getUrlMappings(loaded)).contains("/valid/*")); } @Test public void customLoadOnStartup() { - this.contextLoader.env("spring.webservices.servlet.load-on-startup=1") - .load(context -> { - ServletRegistrationBean registrationBean = context + this.context.withPropertyValues("spring.webservices.servlet.load-on-startup=1") + .run((loaded) -> { + ServletRegistrationBean registrationBean = loaded .getBean(ServletRegistrationBean.class); assertThat(ReflectionTestUtils.getField(registrationBean, "loadOnStartup")).isEqualTo(1); @@ -91,15 +88,22 @@ public class WebServicesAutoConfigurationTests { @Test public void customInitParameters() { - this.contextLoader.env("spring.webservices.servlet.init.key1=value1", - "spring.webservices.servlet.init.key2=value2").load(context -> { - ServletRegistrationBean registrationBean = context - .getBean(ServletRegistrationBean.class); - assertThat(registrationBean.getInitParameters()).containsEntry("key1", - "value1"); - assertThat(registrationBean.getInitParameters()).containsEntry("key2", - "value2"); - }); + this.context + .withPropertyValues("spring.webservices.servlet.init.key1=value1", + "spring.webservices.servlet.init.key2=value2") + .run(loaded -> assertThat( + getServletRegistrationBean(loaded).getInitParameters()) + .containsEntry("key1", "value1") + .containsEntry("key2", "value2")); + } + + private Collection getUrlMappings(ApplicationContext loaded) { + return getServletRegistrationBean(loaded).getUrlMappings(); + } + + private ServletRegistrationBean getServletRegistrationBean( + ApplicationContext loaded) { + return loaded.getBean(ServletRegistrationBean.class); } } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index aedc5e09e54..d60ad2c24ec 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -20,7 +20,8 @@ import javax.sql.DataSource; import org.junit.Test; -import org.springframework.boot.test.context.ContextLoader; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.ApplicationContextTester; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; @@ -37,29 +38,32 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class TestDatabaseAutoConfigurationTests { - private final ContextLoader contextLoader = ContextLoader.standard() - .autoConfig(TestDatabaseAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withConfiguration( + AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test public void replaceWithNoDataSourceAvailable() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(DataSource.class)).isEmpty(); - }); + this.context + .run((loaded) -> assertThat(loaded).doesNotHaveBean(DataSource.class)); } @Test public void replaceWithUniqueDatabase() { - this.contextLoader.config(ExistingDataSourceConfiguration.class).load(context -> { - DataSource datasource = context.getBean(DataSource.class); - JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); - jdbcTemplate.execute("create table example (id int, name varchar);"); - this.contextLoader.load(anotherContext -> { - DataSource anotherDatasource = anotherContext.getBean(DataSource.class); - JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource); - anotherJdbcTemplate - .execute("create table example (id int, name varchar);"); - }); - }); + this.context.withUserConfiguration(ExistingDataSourceConfiguration.class) + .run((loaded) -> { + DataSource datasource = loaded.getBean(DataSource.class); + JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); + jdbcTemplate.execute("create table example (id int, name varchar);"); + this.context.run((secondContext) -> { + DataSource anotherDatasource = secondContext + .getBean(DataSource.class); + JdbcTemplate anotherJdbcTemplate = new JdbcTemplate( + anotherDatasource); + anotherJdbcTemplate + .execute("create table example (id int, name varchar);"); + }); + }); } @Configuration diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java index ce1831ee842..0107e376c9e 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java @@ -22,8 +22,9 @@ import org.junit.Test; import org.junit.runner.RunWith; 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.ContextLoader; +import org.springframework.boot.test.context.ApplicationContextTester; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.context.annotation.Bean; @@ -43,31 +44,32 @@ import static org.mockito.Mockito.mock; @ClassPathExclusions({ "h2-*.jar", "hsqldb-*.jar", "derby-*.jar" }) public class TestDatabaseAutoConfigurationNoEmbeddedTests { - private final ContextLoader contextLoader = ContextLoader.standard() - .config(ExistingDataSourceConfiguration.class) - .autoConfig(TestDatabaseAutoConfiguration.class); + private final ApplicationContextTester context = new ApplicationContextTester() + .withUserConfiguration(ExistingDataSourceConfiguration.class) + .withConfiguration( + AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test public void applyAnyReplace() { - this.contextLoader.loadAndFail(BeanCreationException.class, ex -> { - String message = ex.getMessage(); - assertThat(message).contains( - "Failed to replace DataSource with an embedded database for tests."); - assertThat(message).contains( - "If you want an embedded database please put a supported one on the " - + "classpath"); - assertThat(message).contains( - "or tune the replace attribute of @AutoconfigureTestDatabase."); + this.context.run((loaded) -> { + assertThat(loaded).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") + .hasMessageContaining( + "or tune the replace attribute of @AutoconfigureTestDatabase."); }); } @Test public void applyNoReplace() { - this.contextLoader.env("spring.test.database.replace=NONE").load(context -> { - assertThat(context.getBeansOfType(DataSource.class)).hasSize(1); - assertThat(context.getBean(DataSource.class)) - .isSameAs(context.getBean("myCustomDataSource")); - }); + this.context.withPropertyValues("spring.test.database.replace=NONE") + .run((loaded) -> { + assertThat(loaded).hasSingleBean(DataSource.class); + assertThat(loaded).getBean(DataSource.class) + .isSameAs(loaded.getBean("myCustomDataSource")); + }); } @Configuration