Fixup tests to use new ApplicationContextTester

Update existing tests that previously use `ContextLoader` to the newly
introduced `*ApplicationContextTester` classes.

See gh-9634
This commit is contained in:
Phillip Webb 2017-07-19 08:52:03 -07:00
parent 24d086066b
commit e1ef2a591f
14 changed files with 1436 additions and 1422 deletions

View File

@ -21,6 +21,7 @@ import java.util.Map;
import javax.sql.DataSource; import javax.sql.DataSource;
import io.searchbox.client.JestClient; import io.searchbox.client.JestClient;
import org.assertj.core.api.Condition;
import org.junit.Test; import org.junit.Test;
import org.neo4j.ogm.session.SessionFactory; 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.RabbitHealthIndicator;
import org.springframework.boot.actuate.health.RedisHealthIndicator; import org.springframework.boot.actuate.health.RedisHealthIndicator;
import org.springframework.boot.actuate.health.SolrHealthIndicator; 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.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration; import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration; 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.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration; import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration; 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.autoconfigure.solr.SolrAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; 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.ContextConsumer;
import org.springframework.boot.test.context.ContextLoader;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.data.cassandra.core.CassandraOperations;
@ -79,81 +84,86 @@ import static org.mockito.Mockito.mock;
*/ */
public class HealthIndicatorAutoConfigurationTests { public class HealthIndicatorAutoConfigurationTests {
public final ContextLoader contextLoader = ContextLoader.standard().autoConfig( public final ApplicationContextTester context = new ApplicationContextTester()
HealthIndicatorAutoConfiguration.class, ManagementServerProperties.class); .withConfiguration(
AutoConfigurations.of(HealthIndicatorAutoConfiguration.class,
ManagementServerProperties.class));
@Test @Test
public void defaultHealthIndicator() { public void defaultHealthIndicator() {
this.contextLoader.env("management.health.diskspace.enabled:false") this.context.withPropertyValues("management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void defaultHealthIndicatorsDisabled() { public void defaultHealthIndicatorsDisabled() {
this.contextLoader.env("management.health.defaults.enabled:false") this.context.withPropertyValues("management.health.defaults.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void defaultHealthIndicatorsDisabledWithCustomOne() { public void defaultHealthIndicatorsDisabledWithCustomOne() {
this.contextLoader.config(CustomHealthIndicator.class) this.context.withUserConfiguration(CustomHealthIndicator.class)
.env("management.health.defaults.enabled:false").load(context -> { .withPropertyValues("management.health.defaults.enabled:false")
Map<String, HealthIndicator> beans = context .run((loaded) -> {
Map<String, HealthIndicator> beans = loaded
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertThat(beans).hasSize(1); assertThat(beans).hasSize(1);
assertThat(context.getBean("customHealthIndicator")) assertThat(loaded.getBean("customHealthIndicator"))
.isSameAs(beans.values().iterator().next()); .isSameAs(beans.values().iterator().next());
}); });
} }
@Test @Test
public void defaultHealthIndicatorsDisabledButOne() { public void defaultHealthIndicatorsDisabledButOne() {
this.contextLoader this.context
.env("management.health.defaults.enabled:false", .withPropertyValues("management.health.defaults.enabled:false",
"management.health.diskspace.enabled:true") "management.health.diskspace.enabled:true")
.load(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class)); .run(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class));
} }
@Test @Test
public void redisHealthIndicator() { public void redisHealthIndicator() {
this.contextLoader.autoConfigFirst(RedisAutoConfiguration.class) this.context
.env("management.health.diskspace.enabled:false") .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class))
.load(hasSingleHealthIndicator(RedisHealthIndicator.class)); .withPropertyValues("management.health.diskspace.enabled:false")
.run(hasSingleHealthIndicator(RedisHealthIndicator.class));
} }
@Test @Test
public void notRedisHealthIndicator() { public void notRedisHealthIndicator() {
this.contextLoader.autoConfigFirst(RedisAutoConfiguration.class) this.context
.env("management.health.redis.enabled:false", .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class))
.withPropertyValues("management.health.redis.enabled:false",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void mongoHealthIndicator() { public void mongoHealthIndicator() {
this.contextLoader this.context
.autoConfigFirst(MongoAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class) MongoDataAutoConfiguration.class))
.env("management.health.diskspace.enabled:false") .withPropertyValues("management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(MongoHealthIndicator.class)); .run(hasSingleHealthIndicator(MongoHealthIndicator.class));
} }
@Test @Test
public void notMongoHealthIndicator() { public void notMongoHealthIndicator() {
this.contextLoader this.context
.autoConfigFirst(MongoAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class) MongoDataAutoConfiguration.class))
.env("management.health.mongo.enabled:false", .withPropertyValues("management.health.mongo.enabled:false",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void combinedHealthIndicator() { public void combinedHealthIndicator() {
this.contextLoader.autoConfigFirst(MongoAutoConfiguration.class, this.context.withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class,
RedisAutoConfiguration.class, MongoDataAutoConfiguration.class, RedisAutoConfiguration.class, MongoDataAutoConfiguration.class,
SolrAutoConfiguration.class).load(context -> { SolrAutoConfiguration.class)).run((loaded) -> {
Map<String, HealthIndicator> beans = context Map<String, HealthIndicator> beans = loaded
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertThat(beans).hasSize(4); assertThat(beans).hasSize(4);
}); });
@ -161,17 +171,21 @@ public class HealthIndicatorAutoConfigurationTests {
@Test @Test
public void dataSourceHealthIndicator() { public void dataSourceHealthIndicator() {
this.contextLoader.autoConfigFirst(EmbeddedDataSourceConfiguration.class) this.context
.env("management.health.diskspace.enabled:false") .withConfiguration(
.load(hasSingleHealthIndicator(DataSourceHealthIndicator.class)); AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("management.health.diskspace.enabled:false")
.run(hasSingleHealthIndicator(DataSourceHealthIndicator.class));
} }
@Test @Test
public void dataSourceHealthIndicatorWithSeveralDataSources() { public void dataSourceHealthIndicatorWithSeveralDataSources() {
this.contextLoader this.context
.config(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class) .withUserConfiguration(EmbeddedDataSourceConfiguration.class,
.env("management.health.diskspace.enabled:false").load(context -> { DataSourceConfig.class)
Map<String, HealthIndicator> beans = context .withPropertyValues("management.health.diskspace.enabled:false")
.run((loaded) -> {
Map<String, HealthIndicator> beans = loaded
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertThat(beans).hasSize(1); assertThat(beans).hasSize(1);
HealthIndicator bean = beans.values().iterator().next(); HealthIndicator bean = beans.values().iterator().next();
@ -183,23 +197,24 @@ public class HealthIndicatorAutoConfigurationTests {
@Test @Test
public void dataSourceHealthIndicatorWithAbstractRoutingDataSource() { public void dataSourceHealthIndicatorWithAbstractRoutingDataSource() {
this.contextLoader this.context
.config(EmbeddedDataSourceConfiguration.class, .withUserConfiguration(EmbeddedDataSourceConfiguration.class,
RoutingDatasourceConfig.class) RoutingDatasourceConfig.class)
.env("management.health.diskspace.enabled:false") .withPropertyValues("management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(DataSourceHealthIndicator.class)); .run(hasSingleHealthIndicator(DataSourceHealthIndicator.class));
} }
@Test @Test
public void dataSourceHealthIndicatorWithCustomValidationQuery() { public void dataSourceHealthIndicatorWithCustomValidationQuery() {
this.contextLoader this.context
.config(DataSourceConfig.class, .withUserConfiguration(DataSourceConfig.class,
DataSourcePoolMetadataProvidersConfiguration.class, DataSourcePoolMetadataProvidersConfiguration.class,
HealthIndicatorAutoConfiguration.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") "management.health.diskspace.enabled:false")
.load(context -> { .run((loaded) -> {
Map<String, HealthIndicator> beans = context Map<String, HealthIndicator> beans = loaded
.getBeansOfType(HealthIndicator.class); .getBeansOfType(HealthIndicator.class);
assertThat(beans).hasSize(1); assertThat(beans).hasSize(1);
HealthIndicator healthIndicator = beans.values().iterator().next(); HealthIndicator healthIndicator = beans.values().iterator().next();
@ -213,178 +228,192 @@ public class HealthIndicatorAutoConfigurationTests {
@Test @Test
public void notDataSourceHealthIndicator() { public void notDataSourceHealthIndicator() {
this.contextLoader.config(EmbeddedDataSourceConfiguration.class) this.context.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.env("management.health.db.enabled:false", .withPropertyValues("management.health.db.enabled:false",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void rabbitHealthIndicator() { public void rabbitHealthIndicator() {
this.contextLoader.autoConfigFirst(RabbitAutoConfiguration.class) this.context
.env("management.health.diskspace.enabled:false") .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class))
.load(hasSingleHealthIndicator(RabbitHealthIndicator.class)); .withPropertyValues("management.health.diskspace.enabled:false")
.run(hasSingleHealthIndicator(RabbitHealthIndicator.class));
} }
@Test @Test
public void notRabbitHealthIndicator() { public void notRabbitHealthIndicator() {
this.contextLoader.autoConfigFirst(RabbitAutoConfiguration.class) this.context
.env("management.health.rabbit.enabled:false", .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class))
.withPropertyValues("management.health.rabbit.enabled:false",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void solrHealthIndicator() { public void solrHealthIndicator() {
this.contextLoader.autoConfigFirst(SolrAutoConfiguration.class) this.context.withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class))
.env("management.health.diskspace.enabled:false") .withPropertyValues("management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(SolrHealthIndicator.class)); .run(hasSingleHealthIndicator(SolrHealthIndicator.class));
} }
@Test @Test
public void notSolrHealthIndicator() { public void notSolrHealthIndicator() {
this.contextLoader.autoConfigFirst(SolrAutoConfiguration.class) this.context.withConfiguration(AutoConfigurations.of(SolrAutoConfiguration.class))
.env("management.health.solr.enabled:false", .withPropertyValues("management.health.solr.enabled:false",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void diskSpaceHealthIndicator() { public void diskSpaceHealthIndicator() {
this.contextLoader.load(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class)); this.context.run(hasSingleHealthIndicator(DiskSpaceHealthIndicator.class));
} }
@Test @Test
public void mailHealthIndicator() { public void mailHealthIndicator() {
this.contextLoader.autoConfigFirst(MailSenderAutoConfiguration.class) this.context
.env("spring.mail.host:smtp.acme.org", .withConfiguration(
AutoConfigurations.of(MailSenderAutoConfiguration.class))
.withPropertyValues("spring.mail.host:smtp.acme.org",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(MailHealthIndicator.class)); .run(hasSingleHealthIndicator(MailHealthIndicator.class));
} }
@Test @Test
public void notMailHealthIndicator() { public void notMailHealthIndicator() {
this.contextLoader.autoConfigFirst(MailSenderAutoConfiguration.class) this.context
.env("spring.mail.host:smtp.acme.org", .withConfiguration(
AutoConfigurations.of(MailSenderAutoConfiguration.class))
.withPropertyValues("spring.mail.host:smtp.acme.org",
"management.health.mail.enabled:false", "management.health.mail.enabled:false",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void jmsHealthIndicator() { public void jmsHealthIndicator() {
this.contextLoader.autoConfigFirst(ActiveMQAutoConfiguration.class) this.context
.env("management.health.diskspace.enabled:false") .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class))
.load(hasSingleHealthIndicator(JmsHealthIndicator.class)); .withPropertyValues("management.health.diskspace.enabled:false")
.run(hasSingleHealthIndicator(JmsHealthIndicator.class));
} }
@Test @Test
public void notJmsHealthIndicator() { public void notJmsHealthIndicator() {
this.contextLoader.autoConfigFirst(ActiveMQAutoConfiguration.class) this.context
.env("management.health.jms.enabled:false", .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class))
.withPropertyValues("management.health.jms.enabled:false",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void elasticsearchHealthIndicator() { public void elasticsearchHealthIndicator() {
this.contextLoader this.context
.autoConfigFirst(JestClientConfiguration.class, .withConfiguration(AutoConfigurations.of(JestClientConfiguration.class,
JestAutoConfiguration.class, ElasticsearchAutoConfiguration.class) JestAutoConfiguration.class,
.env("spring.data.elasticsearch.cluster-nodes:localhost:0", ElasticsearchAutoConfiguration.class))
.withPropertyValues("spring.data.elasticsearch.cluster-nodes:localhost:0",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.systemProperty("es.set.netty.runtime.available.processors", "false") .withSystemProperties("es.set.netty.runtime.available.processors=false")
.load(hasSingleHealthIndicator(ElasticsearchHealthIndicator.class)); .run(hasSingleHealthIndicator(ElasticsearchHealthIndicator.class));
} }
@Test @Test
public void elasticsearchJestHealthIndicator() { public void elasticsearchJestHealthIndicator() {
this.contextLoader this.context
.autoConfigFirst(JestClientConfiguration.class, .withConfiguration(AutoConfigurations.of(JestClientConfiguration.class,
JestAutoConfiguration.class) JestAutoConfiguration.class))
.env("management.health.diskspace.enabled:false") .withPropertyValues("management.health.diskspace.enabled:false")
.systemProperty("es.set.netty.runtime.available.processors", "false") .withSystemProperties("es.set.netty.runtime.available.processors=false")
.load(hasSingleHealthIndicator(ElasticsearchJestHealthIndicator.class)); .run(hasSingleHealthIndicator(ElasticsearchJestHealthIndicator.class));
} }
@Test @Test
public void notElasticsearchHealthIndicator() { public void notElasticsearchHealthIndicator() {
this.contextLoader this.context
.autoConfigFirst(JestClientConfiguration.class, .withConfiguration(AutoConfigurations.of(JestClientConfiguration.class,
JestAutoConfiguration.class, ElasticsearchAutoConfiguration.class) JestAutoConfiguration.class,
.env("management.health.elasticsearch.enabled:false", ElasticsearchAutoConfiguration.class))
.withPropertyValues("management.health.elasticsearch.enabled:false",
"spring.data.elasticsearch.properties.path.home:target", "spring.data.elasticsearch.properties.path.home:target",
"management.health.diskspace.enabled:false") "management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void cassandraHealthIndicator() throws Exception { public void cassandraHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(CassandraConfiguration.class) this.context
.env("management.health.diskspace.enabled:false") .withConfiguration(AutoConfigurations.of(CassandraConfiguration.class))
.load(hasSingleHealthIndicator(CassandraHealthIndicator.class)); .withPropertyValues("management.health.diskspace.enabled:false")
.run(hasSingleHealthIndicator(CassandraHealthIndicator.class));
} }
@Test @Test
public void notCassandraHealthIndicator() throws Exception { public void notCassandraHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(CassandraConfiguration.class) this.context
.env("management.health.diskspace.enabled:false", .withConfiguration(AutoConfigurations.of(CassandraConfiguration.class))
.withPropertyValues("management.health.diskspace.enabled:false",
"management.health.cassandra.enabled:false") "management.health.cassandra.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void couchbaseHealthIndicator() throws Exception { public void couchbaseHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(CouchbaseConfiguration.class) this.context
.env("management.health.diskspace.enabled:false") .withConfiguration(AutoConfigurations.of(CouchbaseConfiguration.class))
.load(hasSingleHealthIndicator(CouchbaseHealthIndicator.class)); .withPropertyValues("management.health.diskspace.enabled:false")
.run(hasSingleHealthIndicator(CouchbaseHealthIndicator.class));
} }
@Test @Test
public void notCouchbaseHealthIndicator() throws Exception { public void notCouchbaseHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(CouchbaseConfiguration.class) this.context
.env("management.health.diskspace.enabled:false", .withConfiguration(AutoConfigurations.of(CouchbaseConfiguration.class))
.withPropertyValues("management.health.diskspace.enabled:false",
"management.health.couchbase.enabled:false") "management.health.couchbase.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void ldapHealthIndicator() throws Exception { public void ldapHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(LdapConfiguration.class) this.context.withConfiguration(AutoConfigurations.of(LdapConfiguration.class))
.env("management.health.diskspace.enabled:false") .withPropertyValues("management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(LdapHealthIndicator.class)); .run(hasSingleHealthIndicator(LdapHealthIndicator.class));
} }
@Test @Test
public void notLdapHealthIndicator() throws Exception { public void notLdapHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(LdapConfiguration.class) this.context.withConfiguration(AutoConfigurations.of(LdapConfiguration.class))
.env("management.health.diskspace.enabled:false", .withPropertyValues("management.health.diskspace.enabled:false",
"management.health.ldap.enabled:false") "management.health.ldap.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
@Test @Test
public void neo4jHealthIndicator() throws Exception { public void neo4jHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(Neo4jConfiguration.class) this.context.withConfiguration(AutoConfigurations.of(Neo4jConfiguration.class))
.env("management.health.diskspace.enabled:false") .withPropertyValues("management.health.diskspace.enabled:false")
.load(hasSingleHealthIndicator(Neo4jHealthIndicator.class)); .run(hasSingleHealthIndicator(Neo4jHealthIndicator.class));
} }
@Test @Test
public void notNeo4jHealthIndicator() throws Exception { public void notNeo4jHealthIndicator() throws Exception {
this.contextLoader.autoConfigFirst(Neo4jConfiguration.class) this.context.withConfiguration(AutoConfigurations.of(Neo4jConfiguration.class))
.env("management.health.diskspace.enabled:false", .withPropertyValues("management.health.diskspace.enabled:false",
"management.health.neo4j.enabled:false") "management.health.neo4j.enabled:false")
.load(hasSingleHealthIndicator(ApplicationHealthIndicator.class)); .run(hasSingleHealthIndicator(ApplicationHealthIndicator.class));
} }
private ContextConsumer hasSingleHealthIndicator( private ContextConsumer<AssertableApplicationContext> hasSingleHealthIndicator(
Class<? extends HealthIndicator> type) { Class<? extends HealthIndicator> type) {
return context -> { return (loaded) -> {
Map<String, HealthIndicator> beans = context assertThat(loaded).getBeans(HealthIndicator.class).hasSize(1)
.getBeansOfType(HealthIndicator.class); .hasValueSatisfying(new Condition<>(
assertThat(beans).hasSize(1); (indicator) -> indicator.getClass().equals(type),
assertThat(beans.values().iterator().next().getClass()).isEqualTo(type); "Wrong indicator type"));
}; };
} }
@ -429,6 +458,7 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Configuration @Configuration
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
protected static class CassandraConfiguration { protected static class CassandraConfiguration {
@Bean @Bean
@ -439,6 +469,7 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Configuration @Configuration
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
protected static class CouchbaseConfiguration { protected static class CouchbaseConfiguration {
@Bean @Bean
@ -448,6 +479,7 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Configuration
protected static class JestClientConfiguration { protected static class JestClientConfiguration {
@Bean @Bean
@ -458,6 +490,7 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Configuration @Configuration
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
protected static class LdapConfiguration { protected static class LdapConfiguration {
@Bean @Bean
@ -468,6 +501,7 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Configuration @Configuration
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
protected static class Neo4jConfiguration { protected static class Neo4jConfiguration {
@Bean @Bean

View File

@ -52,10 +52,12 @@ import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanCreationException; 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.cache.support.MockCachingProvider;
import org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration; 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.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.cache.Cache; 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.jcache.JCacheCacheManager;
import org.springframework.cache.support.NoOpCacheManager; import org.springframework.cache.support.NoOpCacheManager;
import org.springframework.cache.support.SimpleCacheManager; import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
@ -101,85 +102,88 @@ public class CacheAutoConfigurationTests {
@Rule @Rule
public final ExpectedException thrown = ExpectedException.none(); public final ExpectedException thrown = ExpectedException.none();
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(CacheAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class));
@Test @Test
public void noEnableCaching() { public void noEnableCaching() {
this.contextLoader.config(EmptyConfiguration.class).load(context -> { this.context.withUserConfiguration(EmptyConfiguration.class).run((loaded) -> {
this.thrown.expect(NoSuchBeanDefinitionException.class); assertThat(loaded).doesNotHaveBean(CacheManager.class);
context.getBean(CacheManager.class);
}); });
} }
@Test @Test
public void cacheManagerBackOff() { public void cacheManagerBackOff() {
this.contextLoader.config(CustomCacheManagerConfiguration.class).load(context -> { this.context.withUserConfiguration(CustomCacheManagerConfiguration.class)
ConcurrentMapCacheManager cacheManager = validateCacheManager(context, .run((loaded) -> {
ConcurrentMapCacheManager.class); assertThat(getCacheManager(loaded, ConcurrentMapCacheManager.class)
assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); .getCacheNames()).containsOnly("custom1");
}); });
} }
@Test @Test
public void cacheManagerFromSupportBackOff() { public void cacheManagerFromSupportBackOff() {
this.contextLoader.config(CustomCacheManagerFromSupportConfiguration.class) this.context
.load(context -> { .withUserConfiguration(CustomCacheManagerFromSupportConfiguration.class)
ConcurrentMapCacheManager cacheManager = validateCacheManager(context, .run((loaded) -> {
ConcurrentMapCacheManager.class); assertThat(getCacheManager(loaded, ConcurrentMapCacheManager.class)
assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); .getCacheNames()).containsOnly("custom1");
}); });
} }
@Test @Test
public void cacheResolverFromSupportBackOff() throws Exception { public void cacheResolverFromSupportBackOff() throws Exception {
this.contextLoader.config(CustomCacheResolverFromSupportConfiguration.class) this.context
.load(context -> { .withUserConfiguration(CustomCacheResolverFromSupportConfiguration.class)
this.thrown.expect(NoSuchBeanDefinitionException.class); .run((loaded) -> {
context.getBean(CacheManager.class); assertThat(loaded).doesNotHaveBean(CacheManager.class);
}); });
} }
@Test @Test
public void customCacheResolverCanBeDefined() throws Exception { public void customCacheResolverCanBeDefined() throws Exception {
this.contextLoader.config(SpecificCacheResolverConfiguration.class) this.context.withUserConfiguration(SpecificCacheResolverConfiguration.class)
.env("spring.cache.type=simple").load(context -> { .withPropertyValues("spring.cache.type=simple").run((loaded) -> {
validateCacheManager(context, ConcurrentMapCacheManager.class); getCacheManager(loaded, ConcurrentMapCacheManager.class);
assertThat(context.getBeansOfType(CacheResolver.class)).hasSize(1); assertThat(loaded).getBeans(CacheResolver.class).hasSize(1);
}); });
} }
@Test @Test
public void notSupportedCachingMode() { public void notSupportedCachingMode() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=foobar").loadAndFail(BeanCreationException.class, .withPropertyValues("spring.cache.type=foobar").run((loaded) -> {
ex -> assertThat(ex.getMessage()).contains( assertThat(loaded).getFailure()
"Failed to bind properties under 'spring.cache.type'")); .isInstanceOf(BeanCreationException.class)
.hasMessageContaining(
"Failed to bind properties under 'spring.cache.type'");
});
} }
@Test @Test
public void simpleCacheExplicit() { public void simpleCacheExplicit() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=simple").load(context -> { .withPropertyValues("spring.cache.type=simple").run((loaded) -> {
ConcurrentMapCacheManager cacheManager = validateCacheManager(context, assertThat(getCacheManager(loaded, ConcurrentMapCacheManager.class)
ConcurrentMapCacheManager.class); .getCacheNames()).isEmpty();
assertThat(cacheManager.getCacheNames()).isEmpty();
}); });
} }
@Test @Test
public void simpleCacheWithCustomizers() { public void simpleCacheWithCustomizers() {
testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "simple", this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class)
"allCacheManagerCustomizer", "simpleCacheManagerCustomizer"); .withPropertyValues("spring.cache.type=" + "simple")
.run(dunno("allCacheManagerCustomizer", "simpleCacheManagerCustomizer"));
} }
@Test @Test
public void simpleCacheExplicitWithCacheNames() { public void simpleCacheExplicitWithCacheNames() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", .withPropertyValues("spring.cache.type=simple",
"spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
ConcurrentMapCacheManager cacheManager = validateCacheManager(context, ConcurrentMapCacheManager cacheManager = getCacheManager(loaded,
ConcurrentMapCacheManager.class); ConcurrentMapCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
}); });
@ -187,50 +191,56 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void genericCacheWithCaches() { public void genericCacheWithCaches() {
this.contextLoader.config(GenericCacheConfiguration.class).load(context -> { this.context.withUserConfiguration(GenericCacheConfiguration.class)
SimpleCacheManager cacheManager = validateCacheManager(context, .run((loaded) -> {
SimpleCacheManager.class); SimpleCacheManager cacheManager = getCacheManager(loaded,
assertThat(cacheManager.getCache("first")) SimpleCacheManager.class);
.isEqualTo(context.getBean("firstCache")); assertThat(cacheManager.getCache("first"))
assertThat(cacheManager.getCache("second")) .isEqualTo(loaded.getBean("firstCache"));
.isEqualTo(context.getBean("secondCache")); assertThat(cacheManager.getCache("second"))
assertThat(cacheManager.getCacheNames()).hasSize(2); .isEqualTo(loaded.getBean("secondCache"));
}); assertThat(cacheManager.getCacheNames()).hasSize(2);
});
} }
@Test @Test
public void genericCacheExplicit() { public void genericCacheExplicit() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=generic").loadAndFail(BeanCreationException.class, .withPropertyValues("spring.cache.type=generic").run((loaded) -> {
ex -> assertThat(ex.getMessage()).contains( assertThat(loaded).getFailure()
"No cache manager could be auto-configured", "GENERIC")); .isInstanceOf(BeanCreationException.class)
.hasMessageContaining(
"No cache manager could be auto-configured")
.hasMessageContaining("GENERIC");
});
} }
@Test @Test
public void genericCacheWithCustomizers() { public void genericCacheWithCustomizers() {
testCustomizers(GenericCacheAndCustomizersConfiguration.class, "generic", this.context.withUserConfiguration(GenericCacheAndCustomizersConfiguration.class)
"allCacheManagerCustomizer", "genericCacheManagerCustomizer"); .withPropertyValues("spring.cache.type=" + "generic")
.run(dunno("allCacheManagerCustomizer", "genericCacheManagerCustomizer"));
} }
@Test @Test
public void genericCacheExplicitWithCaches() { public void genericCacheExplicitWithCaches() {
this.contextLoader.config(GenericCacheConfiguration.class) this.context.withUserConfiguration(GenericCacheConfiguration.class)
.env("spring.cache.type=generic").load(context -> { .withPropertyValues("spring.cache.type=generic").run((loaded) -> {
SimpleCacheManager cacheManager = validateCacheManager(context, SimpleCacheManager cacheManager = getCacheManager(loaded,
SimpleCacheManager.class); SimpleCacheManager.class);
assertThat(cacheManager.getCache("first")) assertThat(cacheManager.getCache("first"))
.isEqualTo(context.getBean("firstCache")); .isEqualTo(loaded.getBean("firstCache"));
assertThat(cacheManager.getCache("second")) assertThat(cacheManager.getCache("second"))
.isEqualTo(context.getBean("secondCache")); .isEqualTo(loaded.getBean("secondCache"));
assertThat(cacheManager.getCacheNames()).hasSize(2); assertThat(cacheManager.getCacheNames()).hasSize(2);
}); });
} }
@Test @Test
public void couchbaseCacheExplicit() { public void couchbaseCacheExplicit() {
this.contextLoader.config(CouchbaseCacheConfiguration.class) this.context.withUserConfiguration(CouchbaseCacheConfiguration.class)
.env("spring.cache.type=couchbase").load(context -> { .withPropertyValues("spring.cache.type=couchbase").run((loaded) -> {
CouchbaseCacheManager cacheManager = validateCacheManager(context, CouchbaseCacheManager cacheManager = getCacheManager(loaded,
CouchbaseCacheManager.class); CouchbaseCacheManager.class);
assertThat(cacheManager.getCacheNames()).isEmpty(); assertThat(cacheManager.getCacheNames()).isEmpty();
}); });
@ -238,70 +248,77 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void couchbaseCacheWithCustomizers() { public void couchbaseCacheWithCustomizers() {
testCustomizers(CouchbaseCacheAndCustomizersConfiguration.class, "couchbase", this.context
"allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer"); .withUserConfiguration(CouchbaseCacheAndCustomizersConfiguration.class)
.withPropertyValues("spring.cache.type=" + "couchbase").run(dunno(
"allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer"));
} }
@Test @Test
public void couchbaseCacheExplicitWithCaches() { public void couchbaseCacheExplicitWithCaches() {
this.contextLoader.config(CouchbaseCacheConfiguration.class) this.context.withUserConfiguration(CouchbaseCacheConfiguration.class)
.env("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", .withPropertyValues("spring.cache.type=couchbase",
"spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
CouchbaseCacheManager cacheManager = validateCacheManager(context, CouchbaseCacheManager cacheManager = getCacheManager(loaded,
CouchbaseCacheManager.class); CouchbaseCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
Cache cache = cacheManager.getCache("foo"); Cache cache = cacheManager.getCache("foo");
assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(cache).isInstanceOf(CouchbaseCache.class);
assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(0); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(0);
assertThat(((CouchbaseCache) cache).getNativeCache()) assertThat(((CouchbaseCache) cache).getNativeCache())
.isEqualTo(context.getBean("bucket")); .isEqualTo(loaded.getBean("bucket"));
}); });
} }
@Test @Test
public void couchbaseCacheExplicitWithTtl() { public void couchbaseCacheExplicitWithTtl() {
this.contextLoader.config(CouchbaseCacheConfiguration.class) this.context.withUserConfiguration(CouchbaseCacheConfiguration.class)
.env("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", .withPropertyValues("spring.cache.type=couchbase",
"spring.cache.cacheNames=foo,bar",
"spring.cache.couchbase.expiration=2000") "spring.cache.couchbase.expiration=2000")
.load(context -> { .run((loaded) -> {
CouchbaseCacheManager cacheManager = validateCacheManager(context, CouchbaseCacheManager cacheManager = getCacheManager(loaded,
CouchbaseCacheManager.class); CouchbaseCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
Cache cache = cacheManager.getCache("foo"); Cache cache = cacheManager.getCache("foo");
assertThat(cache).isInstanceOf(CouchbaseCache.class); assertThat(cache).isInstanceOf(CouchbaseCache.class);
assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(2); assertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(2);
assertThat(((CouchbaseCache) cache).getNativeCache()) assertThat(((CouchbaseCache) cache).getNativeCache())
.isEqualTo(context.getBean("bucket")); .isEqualTo(loaded.getBean("bucket"));
}); });
} }
@Test @Test
public void redisCacheExplicit() { public void redisCacheExplicit() {
this.contextLoader.config(RedisCacheConfiguration.class) this.context.withUserConfiguration(RedisCacheConfiguration.class)
.env("spring.cache.type=redis").load(context -> { .withPropertyValues("spring.cache.type=redis").run((loaded) -> {
RedisCacheManager cacheManager = validateCacheManager(context, RedisCacheManager cacheManager = getCacheManager(loaded,
RedisCacheManager.class); RedisCacheManager.class);
assertThat(cacheManager.getCacheNames()).isEmpty(); assertThat(cacheManager.getCacheNames()).isEmpty();
assertThat(((org.springframework.data.redis.cache.RedisCacheConfiguration) assertThat(
new DirectFieldAccessor(cacheManager).getPropertyValue( ((org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor(
"defaultCacheConfig")).usePrefix()).isTrue(); cacheManager).getPropertyValue("defaultCacheConfig"))
.usePrefix()).isTrue();
}); });
} }
@Test @Test
public void redisCacheWithCustomizers() { public void redisCacheWithCustomizers() {
testCustomizers(RedisCacheAndCustomizersConfiguration.class, "redis", this.context.withUserConfiguration(RedisCacheAndCustomizersConfiguration.class)
"allCacheManagerCustomizer", "redisCacheManagerCustomizer"); .withPropertyValues("spring.cache.type=" + "redis")
.run(dunno("allCacheManagerCustomizer", "redisCacheManagerCustomizer"));
} }
@Test @Test
public void redisCacheExplicitWithCaches() { public void redisCacheExplicitWithCaches() {
this.contextLoader.config(RedisCacheConfiguration.class) this.context.withUserConfiguration(RedisCacheConfiguration.class)
.env("spring.cache.type=redis", "spring.cache.cacheNames[0]=foo", .withPropertyValues("spring.cache.type=redis",
"spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
RedisCacheManager cacheManager = validateCacheManager(context, RedisCacheManager cacheManager = getCacheManager(loaded,
RedisCacheManager.class); RedisCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
}); });
@ -309,9 +326,9 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void noOpCacheExplicit() { public void noOpCacheExplicit() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=none").load(context -> { .withPropertyValues("spring.cache.type=none").run((loaded) -> {
NoOpCacheManager cacheManager = validateCacheManager(context, NoOpCacheManager cacheManager = getCacheManager(loaded,
NoOpCacheManager.class); NoOpCacheManager.class);
assertThat(cacheManager.getCacheNames()).isEmpty(); assertThat(cacheManager.getCacheNames()).isEmpty();
}); });
@ -319,25 +336,27 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void jCacheCacheNoProviderExplicit() { public void jCacheCacheNoProviderExplicit() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache").loadAndFail(ex -> { .withPropertyValues("spring.cache.type=jcache").run((loaded) -> {
assertThat(ex).isInstanceOf(BeanCreationException.class); assertThat(loaded).getFailure()
assertThat(ex.getMessage()).contains( .isInstanceOf(BeanCreationException.class)
"No cache manager could be auto-configured", "JCACHE"); .hasMessageContaining(
"No cache manager could be auto-configured")
.hasMessageContaining("JCACHE");
}); });
} }
@Test @Test
public void jCacheCacheWithProvider() { public void jCacheCacheWithProvider() {
String cachingProviderFqn = MockCachingProvider.class.getName(); String cachingProviderFqn = MockCachingProvider.class.getName();
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn) "spring.cache.jcache.provider=" + cachingProviderFqn)
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
assertThat(cacheManager.getCacheNames()).isEmpty(); assertThat(cacheManager.getCacheNames()).isEmpty();
assertThat(context.getBean(javax.cache.CacheManager.class)) assertThat(loaded.getBean(javax.cache.CacheManager.class))
.isEqualTo(cacheManager.getCacheManager()); .isEqualTo(cacheManager.getCacheManager());
}); });
} }
@ -345,13 +364,13 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void jCacheCacheWithCaches() { public void jCacheCacheWithCaches() {
String cachingProviderFqn = MockCachingProvider.class.getName(); String cachingProviderFqn = MockCachingProvider.class.getName();
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
}); });
@ -360,16 +379,16 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void jCacheCacheWithCachesAndCustomConfig() { public void jCacheCacheWithCachesAndCustomConfig() {
String cachingProviderFqn = MockCachingProvider.class.getName(); String cachingProviderFqn = MockCachingProvider.class.getName();
this.contextLoader.config(JCacheCustomConfiguration.class) this.context.withUserConfiguration(JCacheCustomConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[0]=one",
"spring.cache.cacheNames[1]=two") "spring.cache.cacheNames[1]=two")
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); assertThat(cacheManager.getCacheNames()).containsOnly("one", "two");
CompleteConfiguration<?, ?> defaultCacheConfiguration = context CompleteConfiguration<?, ?> defaultCacheConfiguration = loaded
.getBean(CompleteConfiguration.class); .getBean(CompleteConfiguration.class);
verify(cacheManager.getCacheManager()).createCache("one", verify(cacheManager.getCacheManager()).createCache("one",
defaultCacheConfiguration); defaultCacheConfiguration);
@ -380,35 +399,38 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void jCacheCacheWithExistingJCacheManager() { public void jCacheCacheWithExistingJCacheManager() {
this.contextLoader.config(JCacheCustomCacheManager.class) this.context.withUserConfiguration(JCacheCustomCacheManager.class)
.env("spring.cache.type=jcache").load(context -> { .withPropertyValues("spring.cache.type=jcache").run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
assertThat(cacheManager.getCacheManager()) assertThat(cacheManager.getCacheManager())
.isEqualTo(context.getBean("customJCacheCacheManager")); .isEqualTo(loaded.getBean("customJCacheCacheManager"));
}); });
} }
@Test @Test
public void jCacheCacheWithUnknownProvider() { public void jCacheCacheWithUnknownProvider() {
String wrongCachingProviderFqn = "org.acme.FooBar"; String wrongCachingProviderClassName = "org.acme.FooBar";
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + wrongCachingProviderFqn) "spring.cache.jcache.provider=" + wrongCachingProviderClassName)
.loadAndFail(BeanCreationException.class, ex -> assertThat( .run((loaded) -> {
ex.getMessage().contains(wrongCachingProviderFqn))); assertThat(loaded).getFailure()
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining(wrongCachingProviderClassName);
});
} }
@Test @Test
public void jCacheCacheWithConfig() { public void jCacheCacheWithConfig() {
String cachingProviderFqn = MockCachingProvider.class.getName(); String cachingProviderFqn = MockCachingProvider.class.getName();
String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
this.contextLoader.config(JCacheCustomConfiguration.class) this.context.withUserConfiguration(JCacheCustomConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.jcache.config=" + configLocation) "spring.cache.jcache.config=" + configLocation)
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
Resource configResource = new ClassPathResource(configLocation); Resource configResource = new ClassPathResource(configLocation);
assertThat(cacheManager.getCacheManager().getURI()) assertThat(cacheManager.getCacheManager().getURI())
@ -420,41 +442,45 @@ public class CacheAutoConfigurationTests {
public void jCacheCacheWithWrongConfig() { public void jCacheCacheWithWrongConfig() {
String cachingProviderFqn = MockCachingProvider.class.getName(); String cachingProviderFqn = MockCachingProvider.class.getName();
String configLocation = "org/springframework/boot/autoconfigure/cache/does-not-exist.xml"; String configLocation = "org/springframework/boot/autoconfigure/cache/does-not-exist.xml";
this.contextLoader.config(JCacheCustomConfiguration.class) this.context.withUserConfiguration(JCacheCustomConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.jcache.config=" + configLocation) "spring.cache.jcache.config=" + configLocation)
.loadAndFail(BeanCreationException.class, .run((loaded) -> {
ex -> assertThat(ex.getMessage()).contains("does not exist", assertThat(loaded).getFailure()
configLocation)); .isInstanceOf(BeanCreationException.class)
.hasMessageContaining("does not exist")
.hasMessageContaining(configLocation);
});
} }
@Test @Test
public void ehcacheCacheWithCaches() { public void ehcacheCacheWithCaches() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=ehcache").load(context -> { .withPropertyValues("spring.cache.type=ehcache").run((loaded) -> {
EhCacheCacheManager cacheManager = validateCacheManager(context, EhCacheCacheManager cacheManager = getCacheManager(loaded,
EhCacheCacheManager.class); EhCacheCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1",
"cacheTest2"); "cacheTest2");
assertThat(context.getBean(net.sf.ehcache.CacheManager.class)) assertThat(loaded.getBean(net.sf.ehcache.CacheManager.class))
.isEqualTo(cacheManager.getCacheManager()); .isEqualTo(cacheManager.getCacheManager());
}); });
} }
@Test @Test
public void ehcacheCacheWithCustomizers() { public void ehcacheCacheWithCustomizers() {
testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "ehcache", this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class)
"allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer"); .withPropertyValues("spring.cache.type=" + "ehcache")
.run(dunno("allCacheManagerCustomizer", "ehcacheCacheManagerCustomizer"));
} }
@Test @Test
public void ehcacheCacheWithConfig() { public void ehcacheCacheWithConfig() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=ehcache", .withPropertyValues("spring.cache.type=ehcache",
"spring.cache.ehcache.config=cache/ehcache-override.xml") "spring.cache.ehcache.config=cache/ehcache-override.xml")
.load(context -> { .run((loaded) -> {
EhCacheCacheManager cacheManager = validateCacheManager(context, EhCacheCacheManager cacheManager = getCacheManager(loaded,
EhCacheCacheManager.class); EhCacheCacheManager.class);
assertThat(cacheManager.getCacheNames()) assertThat(cacheManager.getCacheNames())
.containsOnly("cacheOverrideTest1", "cacheOverrideTest2"); .containsOnly("cacheOverrideTest1", "cacheOverrideTest2");
@ -463,25 +489,25 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void ehcacheCacheWithExistingCacheManager() { public void ehcacheCacheWithExistingCacheManager() {
this.contextLoader.config(EhCacheCustomCacheManager.class) this.context.withUserConfiguration(EhCacheCustomCacheManager.class)
.env("spring.cache.type=ehcache").load(context -> { .withPropertyValues("spring.cache.type=ehcache").run((loaded) -> {
EhCacheCacheManager cacheManager = validateCacheManager(context, EhCacheCacheManager cacheManager = getCacheManager(loaded,
EhCacheCacheManager.class); EhCacheCacheManager.class);
assertThat(cacheManager.getCacheManager()) assertThat(cacheManager.getCacheManager())
.isEqualTo(context.getBean("customEhCacheCacheManager")); .isEqualTo(loaded.getBean("customEhCacheCacheManager"));
}); });
} }
@Test @Test
public void ehcache3AsJCacheWithCaches() { public void ehcache3AsJCacheWithCaches() {
String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String cachingProviderFqn = EhcacheCachingProvider.class.getName();
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
}); });
@ -491,12 +517,12 @@ public class CacheAutoConfigurationTests {
public void ehcache3AsJCacheWithConfig() throws IOException { public void ehcache3AsJCacheWithConfig() throws IOException {
String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String cachingProviderFqn = EhcacheCachingProvider.class.getName();
String configLocation = "ehcache3.xml"; String configLocation = "ehcache3.xml";
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.jcache.config=" + configLocation) "spring.cache.jcache.config=" + configLocation)
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
Resource configResource = new ClassPathResource(configLocation); Resource configResource = new ClassPathResource(configLocation);
@ -508,48 +534,54 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void hazelcastCacheExplicit() { public void hazelcastCacheExplicit() {
this.contextLoader.autoConfigFirst(HazelcastAutoConfiguration.class) this.context
.config(DefaultCacheConfiguration.class) .withConfiguration(
.env("spring.cache.type=hazelcast").load(context -> { AutoConfigurations.of(HazelcastAutoConfiguration.class))
HazelcastCacheManager cacheManager = validateCacheManager(context, .withUserConfiguration(DefaultCacheConfiguration.class)
.withPropertyValues("spring.cache.type=hazelcast").run((loaded) -> {
HazelcastCacheManager cacheManager = getCacheManager(loaded,
HazelcastCacheManager.class); HazelcastCacheManager.class);
// NOTE: the hazelcast implementation knows about a cache in a lazy // NOTE: the hazelcast implementation knows about a cache in a lazy
// manner. // manner.
cacheManager.getCache("defaultCache"); cacheManager.getCache("defaultCache");
assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache");
assertThat(context.getBean(HazelcastInstance.class)) assertThat(loaded.getBean(HazelcastInstance.class))
.isEqualTo(cacheManager.getHazelcastInstance()); .isEqualTo(cacheManager.getHazelcastInstance());
}); });
} }
@Test @Test
public void hazelcastCacheWithCustomizers() { public void hazelcastCacheWithCustomizers() {
testCustomizers(HazelcastCacheAndCustomizersConfiguration.class, "hazelcast", this.context
"allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer"); .withUserConfiguration(HazelcastCacheAndCustomizersConfiguration.class)
.withPropertyValues("spring.cache.type=" + "hazelcast").run(dunno(
"allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer"));
} }
@Test @Test
public void hazelcastCacheWithExistingHazelcastInstance() { public void hazelcastCacheWithExistingHazelcastInstance() {
this.contextLoader.config(HazelcastCustomHazelcastInstance.class) this.context.withUserConfiguration(HazelcastCustomHazelcastInstance.class)
.env("spring.cache.type=hazelcast").load(context -> { .withPropertyValues("spring.cache.type=hazelcast").run((loaded) -> {
HazelcastCacheManager cacheManager = validateCacheManager(context, HazelcastCacheManager cacheManager = getCacheManager(loaded,
HazelcastCacheManager.class); HazelcastCacheManager.class);
assertThat(cacheManager.getHazelcastInstance()) assertThat(cacheManager.getHazelcastInstance())
.isEqualTo(context.getBean("customHazelcastInstance")); .isEqualTo(loaded.getBean("customHazelcastInstance"));
}); });
} }
@Test @Test
public void hazelcastCacheWithHazelcastAutoConfiguration() throws IOException { public void hazelcastCacheWithHazelcastAutoConfiguration() throws IOException {
String hazelcastConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; String hazelcastConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
this.contextLoader.autoConfigFirst(HazelcastAutoConfiguration.class) this.context
.config(DefaultCacheConfiguration.class) .withConfiguration(
.env("spring.cache.type=hazelcast", AutoConfigurations.of(HazelcastAutoConfiguration.class))
.withUserConfiguration(DefaultCacheConfiguration.class)
.withPropertyValues("spring.cache.type=hazelcast",
"spring.hazelcast.config=" + hazelcastConfig) "spring.hazelcast.config=" + hazelcastConfig)
.load(context -> { .run((loaded) -> {
HazelcastCacheManager cacheManager = validateCacheManager(context, HazelcastCacheManager cacheManager = getCacheManager(loaded,
HazelcastCacheManager.class); HazelcastCacheManager.class);
HazelcastInstance hazelcastInstance = context HazelcastInstance hazelcastInstance = loaded
.getBean(HazelcastInstance.class); .getBean(HazelcastInstance.class);
assertThat(cacheManager.getHazelcastInstance()) assertThat(cacheManager.getHazelcastInstance())
.isSameAs(hazelcastInstance); .isSameAs(hazelcastInstance);
@ -564,13 +596,13 @@ public class CacheAutoConfigurationTests {
public void hazelcastAsJCacheWithCaches() { public void hazelcastAsJCacheWithCaches() {
String cachingProviderFqn = HazelcastCachingProvider.class.getName(); String cachingProviderFqn = HazelcastCachingProvider.class.getName();
try { try {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", assertThat(cacheManager.getCacheNames()).containsOnly("foo",
"bar"); "bar");
@ -587,14 +619,13 @@ public class CacheAutoConfigurationTests {
String cachingProviderFqn = HazelcastCachingProvider.class.getName(); String cachingProviderFqn = HazelcastCachingProvider.class.getName();
try { try {
String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderFqn,
"spring.cache.jcache.config=" + configLocation) "spring.cache.jcache.config=" + configLocation)
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
Resource configResource = new ClassPathResource(configLocation); Resource configResource = new ClassPathResource(configLocation);
assertThat(cacheManager.getCacheManager().getURI()) assertThat(cacheManager.getCacheManager().getURI())
.isEqualTo(configResource.getURI()); .isEqualTo(configResource.getURI());
@ -609,20 +640,21 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void hazelcastAsJCacheWithExistingHazelcastInstance() throws IOException { public void hazelcastAsJCacheWithExistingHazelcastInstance() throws IOException {
String cachingProviderFqn = HazelcastCachingProvider.class.getName(); String cachingProviderFqn = HazelcastCachingProvider.class.getName();
this.contextLoader.autoConfig(HazelcastAutoConfiguration.class) this.context
.config(DefaultCacheConfiguration.class) .withConfiguration(
.env("spring.cache.type=jcache", AutoConfigurations.of(HazelcastAutoConfiguration.class))
.withUserConfiguration(DefaultCacheConfiguration.class)
.withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn) "spring.cache.jcache.provider=" + cachingProviderFqn)
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, JCacheCacheManager cacheManager = getCacheManager(loaded,
JCacheCacheManager.class); JCacheCacheManager.class);
javax.cache.CacheManager jCacheManager = cacheManager javax.cache.CacheManager jCacheManager = cacheManager
.getCacheManager(); .getCacheManager();
assertThat(jCacheManager).isInstanceOf( assertThat(jCacheManager).isInstanceOf(
com.hazelcast.cache.HazelcastCacheManager.class); com.hazelcast.cache.HazelcastCacheManager.class);
assertThat(context.getBeansOfType(HazelcastInstance.class)) assertThat(loaded.getBeansOfType(HazelcastInstance.class)).hasSize(1);
.hasSize(1); HazelcastInstance hazelcastInstance = loaded
HazelcastInstance hazelcastInstance = context
.getBean(HazelcastInstance.class); .getBean(HazelcastInstance.class);
assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager) assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager)
.getHazelcastInstance()).isSameAs(hazelcastInstance); .getHazelcastInstance()).isSameAs(hazelcastInstance);
@ -633,113 +665,108 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void infinispanCacheWithConfig() { public void infinispanCacheWithConfig() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=infinispan", .withPropertyValues("spring.cache.type=infinispan",
"spring.cache.infinispan.config=infinispan.xml") "spring.cache.infinispan.config=infinispan.xml")
.load(context -> { .run((loaded) -> {
SpringEmbeddedCacheManager cacheManager = validateCacheManager( SpringEmbeddedCacheManager cacheManager = getCacheManager(loaded,
context, SpringEmbeddedCacheManager.class); SpringEmbeddedCacheManager.class);
assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); assertThat(cacheManager.getCacheNames()).contains("foo", "bar");
}); });
} }
@Test @Test
public void infinispanCacheWithCustomizers() { public void infinispanCacheWithCustomizers() {
testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "infinispan", this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class)
"allCacheManagerCustomizer", "infinispanCacheManagerCustomizer"); .withPropertyValues("spring.cache.type=" + "infinispan").run(dunno(
"allCacheManagerCustomizer", "infinispanCacheManagerCustomizer"));
} }
@Test @Test
public void infinispanCacheWithCaches() { public void infinispanCacheWithCaches() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", .withPropertyValues("spring.cache.type=infinispan",
"spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
SpringEmbeddedCacheManager cacheManager = validateCacheManager( assertThat(getCacheManager(loaded, SpringEmbeddedCacheManager.class)
context, SpringEmbeddedCacheManager.class); .getCacheNames()).containsOnly("foo", "bar");
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
}); });
} }
@Test @Test
public void infinispanCacheWithCachesAndCustomConfig() { public void infinispanCacheWithCachesAndCustomConfig() {
this.contextLoader.config(InfinispanCustomConfiguration.class) this.context.withUserConfiguration(InfinispanCustomConfiguration.class)
.env("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", .withPropertyValues("spring.cache.type=infinispan",
"spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
SpringEmbeddedCacheManager cacheManager = validateCacheManager( assertThat(getCacheManager(loaded, SpringEmbeddedCacheManager.class)
context, SpringEmbeddedCacheManager.class); .getCacheNames()).containsOnly("foo", "bar");
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); verify(loaded.getBean(ConfigurationBuilder.class), times(2)).build();
ConfigurationBuilder defaultConfigurationBuilder = context
.getBean(ConfigurationBuilder.class);
verify(defaultConfigurationBuilder, times(2)).build();
}); });
} }
@Test @Test
public void infinispanAsJCacheWithCaches() { public void infinispanAsJCacheWithCaches() {
String cachingProviderFqn = JCachingProvider.class.getName(); String cachingProviderClassName = JCachingProvider.class.getName();
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderClassName,
"spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context, assertThat(getCacheManager(loaded, JCacheCacheManager.class)
JCacheCacheManager.class); .getCacheNames()).containsOnly("foo", "bar");
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
}); });
} }
@Test @Test
public void infinispanAsJCacheWithConfig() throws IOException { public void infinispanAsJCacheWithConfig() throws IOException {
String cachingProviderFqn = JCachingProvider.class.getName(); String cachingProviderClassName = JCachingProvider.class.getName();
String configLocation = "infinispan.xml"; String configLocation = "infinispan.xml";
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderClassName,
"spring.cache.jcache.config=" + configLocation) "spring.cache.jcache.config=" + configLocation)
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context,
JCacheCacheManager.class);
Resource configResource = new ClassPathResource(configLocation); Resource configResource = new ClassPathResource(configLocation);
assertThat(cacheManager.getCacheManager().getURI()) assertThat(getCacheManager(loaded, JCacheCacheManager.class)
.isEqualTo(configResource.getURI()); .getCacheManager().getURI())
.isEqualTo(configResource.getURI());
}); });
} }
@Test @Test
public void jCacheCacheWithCachesAndCustomizer() { public void jCacheCacheWithCachesAndCustomizer() {
String cachingProviderFqn = HazelcastCachingProvider.class.getName(); String cachingProviderClassName = HazelcastCachingProvider.class.getName();
try { try {
this.contextLoader.config(JCacheWithCustomizerConfiguration.class) this.context.withUserConfiguration(JCacheWithCustomizerConfiguration.class)
.env("spring.cache.type=jcache", .withPropertyValues("spring.cache.type=jcache",
"spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.jcache.provider=" + cachingProviderClassName,
"spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(context -> { .run((loaded) -> {
JCacheCacheManager cacheManager = validateCacheManager(context,
JCacheCacheManager.class);
// see customizer // see customizer
assertThat(cacheManager.getCacheNames()).containsOnly("foo", assertThat(getCacheManager(loaded, JCacheCacheManager.class)
"custom1"); .getCacheNames()).containsOnly("foo", "custom1");
}); });
} }
finally { finally {
Caching.getCachingProvider(cachingProviderFqn).close(); Caching.getCachingProvider(cachingProviderClassName).close();
} }
} }
@Test @Test
public void caffeineCacheWithExplicitCaches() { public void caffeineCacheWithExplicitCaches() {
this.contextLoader.config(DefaultCacheConfiguration.class) this.context.withUserConfiguration(DefaultCacheConfiguration.class)
.env("spring.cache.type=caffeine", "spring.cache.cacheNames=foo") .withPropertyValues("spring.cache.type=caffeine",
.load(context -> { "spring.cache.cacheNames=foo")
CaffeineCacheManager cacheManager = validateCacheManager(context, .run((loaded) -> {
CaffeineCacheManager manager = getCacheManager(loaded,
CaffeineCacheManager.class); CaffeineCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo"); assertThat(manager.getCacheNames()).containsOnly("foo");
Cache foo = cacheManager.getCache("foo"); Cache foo = manager.getCache("foo");
foo.get("1"); foo.get("1");
// See next tests: no spec given so stats should be disabled // See next tests: no spec given so stats should be disabled
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount())
@ -749,74 +776,75 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void caffeineCacheWithCustomizers() { public void caffeineCacheWithCustomizers() {
testCustomizers(DefaultCacheAndCustomizersConfiguration.class, "caffeine", this.context.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class)
"allCacheManagerCustomizer", "caffeineCacheManagerCustomizer"); .withPropertyValues("spring.cache.type=" + "caffeine").run(dunno(
"allCacheManagerCustomizer", "caffeineCacheManagerCustomizer"));
} }
@Test @Test
public void caffeineCacheWithExplicitCacheBuilder() { public void caffeineCacheWithExplicitCacheBuilder() {
this.contextLoader.config(CaffeineCacheBuilderConfiguration.class) this.context.withUserConfiguration(CaffeineCacheBuilderConfiguration.class)
.env("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") .withPropertyValues("spring.cache.type=caffeine",
.load(this::validateCaffeineCacheWithStats); "spring.cache.cacheNames=foo,bar")
.run(this::validateCaffeineCacheWithStats);
} }
@Test @Test
public void caffeineCacheExplicitWithSpec() { public void caffeineCacheExplicitWithSpec() {
this.contextLoader.config(CaffeineCacheSpecConfiguration.class) this.context.withUserConfiguration(CaffeineCacheSpecConfiguration.class)
.env("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", .withPropertyValues("spring.cache.type=caffeine",
"spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar") "spring.cache.cacheNames[1]=bar")
.load(this::validateCaffeineCacheWithStats); .run(this::validateCaffeineCacheWithStats);
} }
@Test @Test
public void caffeineCacheExplicitWithSpecString() { public void caffeineCacheExplicitWithSpecString() {
this.contextLoader.config(DefaultCacheConfiguration.class).env( this.context.withUserConfiguration(DefaultCacheConfiguration.class)
"spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", .withPropertyValues("spring.cache.type=caffeine",
"spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") "spring.cache.caffeine.spec=recordStats",
.load(this::validateCaffeineCacheWithStats); "spring.cache.cacheNames[0]=foo",
"spring.cache.cacheNames[1]=bar")
.run(this::validateCaffeineCacheWithStats);
} }
private void validateCaffeineCacheWithStats(ConfigurableApplicationContext context) { private void validateCaffeineCacheWithStats(AssertableApplicationContext context) {
CaffeineCacheManager cacheManager = validateCacheManager(context, CaffeineCacheManager manager = getCacheManager(context,
CaffeineCacheManager.class); CaffeineCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); assertThat(manager.getCacheNames()).containsOnly("foo", "bar");
Cache foo = cacheManager.getCache("foo"); Cache foo = manager.getCache("foo");
foo.get("1"); foo.get("1");
assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()) assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount())
.isEqualTo(1L); .isEqualTo(1L);
} }
private <T extends CacheManager> T validateCacheManager( @SuppressWarnings("rawtypes")
ConfigurableApplicationContext context, Class<T> type) { private ContextConsumer<AssertableApplicationContext> dunno(
CacheManager cacheManager = context.getBean(CacheManager.class); String... expectedCustomizerNames) {
assertThat(cacheManager).as("Wrong cache manager type").isInstanceOf(type); return (loaded) -> {
return type.cast(cacheManager); CacheManager cacheManager = getCacheManager(loaded, CacheManager.class);
List<String> expected = new ArrayList<>(
Arrays.asList(expectedCustomizerNames));
Map<String, CacheManagerTestCustomizer> 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);
};
} }
@SuppressWarnings("rawtypes") private <T extends CacheManager> T getCacheManager(
private void testCustomizers(Class<?> config, String cacheType, AssertableApplicationContext loaded, Class<T> type) {
String... expectedCustomizerNames) { CacheManager cacheManager = loaded.getBean(CacheManager.class);
this.contextLoader.config(config).env("spring.cache.type=" + cacheType) assertThat(cacheManager).as("Wrong cache manager type").isInstanceOf(type);
.load(context -> { return type.cast(cacheManager);
CacheManager cacheManager = validateCacheManager(context,
CacheManager.class);
List<String> expected = new ArrayList<>();
expected.addAll(Arrays.asList(expectedCustomizerNames));
Map<String, CacheManagerTestCustomizer> map = context
.getBeansOfType(CacheManagerTestCustomizer.class);
for (Map.Entry<String, CacheManagerTestCustomizer> 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);
});
} }
@Configuration @Configuration

View File

@ -23,12 +23,14 @@ import com.hazelcast.client.impl.HazelcastClientProxy;
import com.hazelcast.config.Config; import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast; import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstance;
import org.assertj.core.api.Condition;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException; 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -59,68 +61,72 @@ public class HazelcastAutoConfigurationClientTests {
} }
} }
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(HazelcastAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class));
@Test @Test
public void systemProperty() throws IOException { public void systemProperty() throws IOException {
this.contextLoader this.context
.systemProperty(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY, .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY
"classpath:org/springframework/boot/autoconfigure/hazelcast/" + "=classpath:org/springframework/boot/autoconfigure/hazelcast/"
+ "hazelcast-client-specific.xml") + "hazelcast-client-specific.xml")
.load(context -> { .run((loaded) -> {
HazelcastInstance hazelcastInstance = context assertThat(loaded).getBean(HazelcastInstance.class)
.getBean(HazelcastInstance.class); .isInstanceOf(HazelcastInstance.class)
assertThat(hazelcastInstance) .has(nameStartingWith("hz.client_"));
.isInstanceOf(HazelcastClientProxy.class);
assertThat(hazelcastInstance.getName()).startsWith("hz.client_");
}); });
} }
@Test @Test
public void explicitConfigFile() throws IOException { public void explicitConfigFile() throws IOException {
this.contextLoader this.context
.env("spring.hazelcast.config=org/springframework/boot/autoconfigure/" .withPropertyValues(
+ "hazelcast/hazelcast-client-specific.xml") "spring.hazelcast.config=org/springframework/boot/autoconfigure/"
.load(context -> { + "hazelcast/hazelcast-client-specific.xml")
HazelcastInstance hazelcastInstance = context .run((loaded) -> {
.getBean(HazelcastInstance.class); assertThat(loaded).getBean(HazelcastInstance.class)
assertThat(hazelcastInstance) .isInstanceOf(HazelcastClientProxy.class)
.isInstanceOf(HazelcastClientProxy.class); .has(nameStartingWith("hz.client_"));
assertThat(hazelcastInstance.getName()).startsWith("hz.client_");
}); });
} }
@Test @Test
public void explicitConfigUrl() throws IOException { public void explicitConfigUrl() throws IOException {
this.contextLoader.env("spring.hazelcast.config=hazelcast-client-default.xml") this.context
.load(context -> { .withPropertyValues(
HazelcastInstance hazelcastInstance = context "spring.hazelcast.config=hazelcast-client-default.xml")
.getBean(HazelcastInstance.class); .run((loaded) -> {
assertThat(hazelcastInstance) assertThat(loaded).getBean(HazelcastInstance.class)
.isInstanceOf(HazelcastClientProxy.class); .isInstanceOf(HazelcastClientProxy.class)
assertThat(hazelcastInstance.getName()).startsWith("hz.client_"); .has(nameStartingWith("hz.client_"));
}); });
} }
@Test @Test
public void unknownConfigFile() { public void unknownConfigFile() {
this.contextLoader.env("spring.hazelcast.config=foo/bar/unknown.xml").loadAndFail( this.context.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml")
BeanCreationException.class, .run((loaded) -> {
ex -> assertThat(ex.getMessage()).contains("foo/bar/unknown.xml")); assertThat(loaded).getFailure()
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining("foo/bar/unknown.xml");
});
} }
@Test @Test
public void clientConfigTakesPrecedence() { public void clientConfigTakesPrecedence() {
this.contextLoader.config(HazelcastServerAndClientConfig.class) this.context.withUserConfiguration(HazelcastServerAndClientConfig.class)
.env("spring.hazelcast.config=this-is-ignored.xml").load(context -> { .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml")
HazelcastInstance hazelcastInstance = context .run((loaded) -> {
.getBean(HazelcastInstance.class); assertThat(loaded).getBean(HazelcastInstance.class)
assertThat(hazelcastInstance)
.isInstanceOf(HazelcastClientProxy.class); .isInstanceOf(HazelcastClientProxy.class);
}); });
} }
private Condition<HazelcastInstance> nameStartingWith(String prefix) {
return new Condition<HazelcastInstance>((o) -> o.getName().startsWith(prefix),
"Name starts with " + prefix);
}
@Configuration @Configuration
static class HazelcastServerAndClientConfig { static class HazelcastServerAndClientConfig {

View File

@ -27,7 +27,8 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanCreationException; 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.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -45,44 +46,38 @@ import static org.assertj.core.api.Assertions.assertThat;
@ClassPathExclusions("hazelcast-client-*.jar") @ClassPathExclusions("hazelcast-client-*.jar")
public class HazelcastAutoConfigurationServerTests { public class HazelcastAutoConfigurationServerTests {
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(HazelcastAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class));
@Test @Test
public void defaultConfigFile() throws IOException { public void defaultConfigFile() throws IOException {
// hazelcast.xml present in root classpath // hazelcast.xml present in root classpath
this.contextLoader.load(context -> { this.context.run((loaded) -> {
HazelcastInstance hazelcastInstance = context Config config = loaded.getBean(HazelcastInstance.class).getConfig();
.getBean(HazelcastInstance.class); assertThat(config.getConfigurationUrl())
assertThat(hazelcastInstance.getConfig().getConfigurationUrl())
.isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); .isEqualTo(new ClassPathResource("hazelcast.xml").getURL());
}); });
} }
@Test @Test
public void systemProperty() throws IOException { public void systemProperty() throws IOException {
this.contextLoader this.context
.systemProperty(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY, .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY
"classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")
.load(context -> { .run((loaded) -> {
Config config = loaded.getBean(HazelcastInstance.class).getConfig();
HazelcastInstance hazelcastInstance = context assertThat(config.getQueueConfigs().keySet()).containsOnly("foobar");
.getBean(HazelcastInstance.class);
Map<String, QueueConfig> queueConfigs = hazelcastInstance.getConfig()
.getQueueConfigs();
assertThat(queueConfigs).hasSize(1).containsKey("foobar");
}); });
} }
@Test @Test
public void explicitConfigFile() throws IOException { public void explicitConfigFile() throws IOException {
this.contextLoader this.context.withPropertyValues(
.env("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/"
+ "hazelcast-specific.xml") + "hazelcast-specific.xml")
.load(context -> { .run((loaded) -> {
HazelcastInstance hazelcastInstance = context Config config = loaded.getBean(HazelcastInstance.class).getConfig();
.getBean(HazelcastInstance.class); assertThat(config.getConfigurationFile())
assertThat(hazelcastInstance.getConfig().getConfigurationFile())
.isEqualTo(new ClassPathResource( .isEqualTo(new ClassPathResource(
"org/springframework/boot/autoconfigure/hazelcast" "org/springframework/boot/autoconfigure/hazelcast"
+ "/hazelcast-specific.xml").getFile()); + "/hazelcast-specific.xml").getFile());
@ -91,54 +86,53 @@ public class HazelcastAutoConfigurationServerTests {
@Test @Test
public void explicitConfigUrl() throws IOException { public void explicitConfigUrl() throws IOException {
this.contextLoader.env("spring.hazelcast.config=hazelcast-default.xml") this.context.withPropertyValues("spring.hazelcast.config=hazelcast-default.xml")
.load(context -> { .run((loaded) -> {
HazelcastInstance hazelcastInstance = context Config config = loaded.getBean(HazelcastInstance.class).getConfig();
.getBean(HazelcastInstance.class); assertThat(config.getConfigurationUrl()).isEqualTo(
assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) new ClassPathResource("hazelcast-default.xml").getURL());
.isEqualTo(new ClassPathResource("hazelcast-default.xml")
.getURL());
}); });
} }
@Test @Test
public void unknownConfigFile() { public void unknownConfigFile() {
this.contextLoader.env("spring.hazelcast.config=foo/bar/unknown.xml").loadAndFail( this.context.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml")
BeanCreationException.class, .run((loaded) -> {
ex -> assertThat(ex.getMessage()).contains("foo/bar/unknown.xml")); assertThat(loaded).getFailure()
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining("foo/bar/unknown.xml");
});
} }
@Test @Test
public void configInstanceWithName() { public void configInstanceWithName() {
Config config = new Config("my-test-instance"); Config config = new Config("my-test-instance");
HazelcastInstance existingHazelcastInstance = Hazelcast HazelcastInstance existing = Hazelcast.newHazelcastInstance(config);
.newHazelcastInstance(config);
try { try {
this.contextLoader.config(HazelcastConfigWithName.class) this.context.withUserConfiguration(HazelcastConfigWithName.class)
.env("spring.hazelcast.config=this-is-ignored.xml").load(context -> { .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml")
HazelcastInstance hazelcastInstance = context .run(loaded -> {
HazelcastInstance hazelcast = (loaded)
.getBean(HazelcastInstance.class); .getBean(HazelcastInstance.class);
assertThat(hazelcastInstance.getConfig().getInstanceName()) assertThat(hazelcast.getConfig().getInstanceName())
.isEqualTo("my-test-instance"); .isEqualTo("my-test-instance");
// Should reuse any existing instance by default. // Should reuse any existing instance by default.
assertThat(hazelcastInstance) assertThat(hazelcast).isEqualTo(existing);
.isEqualTo(existingHazelcastInstance);
}); });
} }
finally { finally {
existingHazelcastInstance.shutdown(); existing.shutdown();
} }
} }
@Test @Test
public void configInstanceWithoutName() { public void configInstanceWithoutName() {
this.contextLoader.config(HazelcastConfigNoName.class) this.context.withUserConfiguration(HazelcastConfigNoName.class)
.env("spring.hazelcast.config=this-is-ignored.xml").load(context -> { .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml")
HazelcastInstance hazelcastInstance = context .run((loaded) -> {
.getBean(HazelcastInstance.class); Config config = loaded.getBean(HazelcastInstance.class).getConfig();
Map<String, QueueConfig> queueConfigs = hazelcastInstance.getConfig() Map<String, QueueConfig> queueConfigs = config.getQueueConfigs();
.getQueueConfigs(); assertThat(queueConfigs.keySet()).containsOnly("another-queue");
assertThat(queueConfigs).hasSize(1).containsKey("another-queue");
}); });
} }

View File

@ -18,10 +18,12 @@ package org.springframework.boot.autoconfigure.hazelcast;
import java.io.IOException; import java.io.IOException;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstance;
import org.junit.Test; 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 org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -33,16 +35,15 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class HazelcastAutoConfigurationTests { public class HazelcastAutoConfigurationTests {
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(HazelcastAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class));
@Test @Test
public void defaultConfigFile() throws IOException { public void defaultConfigFile() throws IOException {
// no hazelcast-client.xml and hazelcast.xml is present in root classpath // no hazelcast-client.xml and hazelcast.xml is present in root classpath
this.contextLoader.load(context -> { this.context.run((loaded) -> {
HazelcastInstance hazelcastInstance = context Config config = loaded.getBean(HazelcastInstance.class).getConfig();
.getBean(HazelcastInstance.class); assertThat(config.getConfigurationUrl())
assertThat(hazelcastInstance.getConfig().getConfigurationUrl())
.isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); .isEqualTo(new ClassPathResource("hazelcast.xml").getURL());
}); });
} }

View File

@ -37,9 +37,10 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.jdbc.DatabaseDriver; import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.boot.test.context.ContextConsumer; import org.springframework.boot.test.context.ApplicationContextTester;
import org.springframework.boot.test.context.ContextLoader; import org.springframework.boot.test.context.AssertableApplicationContext;
import org.springframework.boot.test.context.HidePackagesClassLoader; import org.springframework.boot.test.context.HidePackagesClassLoader;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -57,22 +58,22 @@ import static org.mockito.Mockito.mock;
*/ */
public class DataSourceAutoConfigurationTests { public class DataSourceAutoConfigurationTests {
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(DataSourceAutoConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class))
.env("spring.datasource.initialize=false", .withPropertyValues("spring.datasource.initialize=false",
"spring.datasource.url:jdbc:hsqldb:mem:testdb-" "spring.datasource.url:jdbc:hsqldb:mem:testdb-"
+ new Random().nextInt()); + new Random().nextInt());
@Test @Test
public void testDefaultDataSourceExists() throws Exception { public void testDefaultDataSourceExists() throws Exception {
this.contextLoader.load( this.context
context -> assertThat(context.getBean(DataSource.class)).isNotNull()); .run((loaded) -> assertThat(loaded).hasSingleBean(DataSource.class));
} }
@Test @Test
public void testDataSourceHasEmbeddedDefault() throws Exception { public void testDataSourceHasEmbeddedDefault() throws Exception {
this.contextLoader.load(context -> { this.context.run((loaded) -> {
HikariDataSource dataSource = context.getBean(HikariDataSource.class); HikariDataSource dataSource = loaded.getBean(HikariDataSource.class);
assertThat(dataSource.getJdbcUrl()).isNotNull(); assertThat(dataSource.getJdbcUrl()).isNotNull();
assertThat(dataSource.getDriverClassName()).isNotNull(); assertThat(dataSource.getDriverClassName()).isNotNull();
}); });
@ -82,8 +83,11 @@ public class DataSourceAutoConfigurationTests {
public void testBadUrl() throws Exception { public void testBadUrl() throws Exception {
try { try {
EmbeddedDatabaseConnection.override = EmbeddedDatabaseConnection.NONE; EmbeddedDatabaseConnection.override = EmbeddedDatabaseConnection.NONE;
this.contextLoader.env("spring.datasource.url:jdbc:not-going-to-work") this.context
.loadAndFail(BeanCreationException.class, ex -> { .withPropertyValues("spring.datasource.url:jdbc:not-going-to-work")
.run((loaded) -> {
assertThat(loaded).getFailure()
.isInstanceOf(BeanCreationException.class);
}); });
} }
finally { finally {
@ -93,10 +97,14 @@ public class DataSourceAutoConfigurationTests {
@Test @Test
public void testBadDriverClass() throws Exception { public void testBadDriverClass() throws Exception {
this.contextLoader.env("spring.datasource.driverClassName:org.none.jdbcDriver") this.context
.loadAndFail(BeanCreationException.class, .withPropertyValues(
ex -> assertThat(ex.getMessage()) "spring.datasource.driverClassName:org.none.jdbcDriver")
.contains("org.none.jdbcDriver")); .run((loaded) -> {
assertThat(loaded).getFailure()
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining("org.none.jdbcDriver");
});
} }
@Test @Test
@ -111,14 +119,14 @@ public class DataSourceAutoConfigurationTests {
public void tomcatIsFallback() throws Exception { public void tomcatIsFallback() throws Exception {
assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class,
Collections.singletonList("com.zaxxer.hikari"), Collections.singletonList("com.zaxxer.hikari"),
dataSource -> assertThat(dataSource.getUrl()) (dataSource) -> assertThat(dataSource.getUrl())
.startsWith("jdbc:hsqldb:mem:testdb")); .startsWith("jdbc:hsqldb:mem:testdb"));
} }
@Test @Test
public void tomcatValidatesConnectionByDefault() { public void tomcatValidatesConnectionByDefault() {
assertDataSource(org.apache.tomcat.jdbc.pool.DataSource.class, 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.isTestOnBorrow()).isTrue();
assertThat(dataSource.getValidationQuery()) assertThat(dataSource.getValidationQuery())
.isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery()); .isEqualTo(DatabaseDriver.HSQLDB.getValidationQuery());
@ -129,14 +137,14 @@ public class DataSourceAutoConfigurationTests {
public void commonsDbcp2IsFallback() throws Exception { public void commonsDbcp2IsFallback() throws Exception {
assertDataSource(BasicDataSource.class, assertDataSource(BasicDataSource.class,
Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"),
dataSource -> assertThat(dataSource.getUrl()) (dataSource) -> assertThat(dataSource.getUrl())
.startsWith("jdbc:hsqldb:mem:testdb")); .startsWith("jdbc:hsqldb:mem:testdb"));
} }
@Test @Test
public void commonsDbcp2ValidatesConnectionByDefault() throws Exception { public void commonsDbcp2ValidatesConnectionByDefault() throws Exception {
assertDataSource(org.apache.commons.dbcp2.BasicDataSource.class, 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.getTestOnBorrow()).isEqualTo(true);
assertThat(dataSource.getValidationQuery()).isNull(); // Use assertThat(dataSource.getValidationQuery()).isNull(); // Use
// Connection#isValid() // Connection#isValid()
@ -144,12 +152,12 @@ public class DataSourceAutoConfigurationTests {
} }
@Test @Test
@SuppressWarnings("resource")
public void testEmbeddedTypeDefaultsUsername() throws Exception { public void testEmbeddedTypeDefaultsUsername() throws Exception {
this.contextLoader.env("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", this.context.withPropertyValues(
"spring.datasource.url:jdbc:hsqldb:mem:testdb").load(context -> { "spring.datasource.driverClassName:org.hsqldb.jdbcDriver",
DataSource bean = context.getBean(DataSource.class); "spring.datasource.url:jdbc:hsqldb:mem:testdb").run((loaded) -> {
assertThat(bean).isNotNull(); DataSource bean = loaded.getBean(DataSource.class);
@SuppressWarnings("resource")
HikariDataSource pool = (HikariDataSource) bean; HikariDataSource pool = (HikariDataSource) bean;
assertThat(pool.getDriverClassName()) assertThat(pool.getDriverClassName())
.isEqualTo("org.hsqldb.jdbcDriver"); .isEqualTo("org.hsqldb.jdbcDriver");
@ -163,62 +171,62 @@ public class DataSourceAutoConfigurationTests {
*/ */
@Test @Test
public void explicitTypeNoSupportedDataSource() { public void explicitTypeNoSupportedDataSource() {
this.contextLoader this.context
.classLoader(new HidePackagesClassLoader("org.apache.tomcat", .withClassLoader(new HidePackagesClassLoader("org.apache.tomcat",
"com.zaxxer.hikari", "org.apache.commons.dbcp", "com.zaxxer.hikari", "org.apache.commons.dbcp",
"org.apache.commons.dbcp2")) "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.url:jdbc:hsqldb:mem:testdb",
"spring.datasource.type:" "spring.datasource.type:"
+ SimpleDriverDataSource.class.getName()) + SimpleDriverDataSource.class.getName())
.load(testExplicitType()); .run(this::containsOnlySimpleDriverDataSource);
} }
@Test @Test
public void explicitTypeSupportedDataSource() { public void explicitTypeSupportedDataSource() {
this.contextLoader this.context
.env("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", .withPropertyValues(
"spring.datasource.driverClassName:org.hsqldb.jdbcDriver",
"spring.datasource.url:jdbc:hsqldb:mem:testdb", "spring.datasource.url:jdbc:hsqldb:mem:testdb",
"spring.datasource.type:" "spring.datasource.type:"
+ SimpleDriverDataSource.class.getName()) + SimpleDriverDataSource.class.getName())
.load(testExplicitType()); .run(this::containsOnlySimpleDriverDataSource);
} }
private ContextConsumer testExplicitType() { private void containsOnlySimpleDriverDataSource(AssertableApplicationContext loaded) {
return context -> { assertThat(loaded).hasSingleBean(DataSource.class);
assertThat(context.getBeansOfType(DataSource.class)).hasSize(1); assertThat(loaded).getBean(DataSource.class)
DataSource bean = context.getBean(DataSource.class); .isExactlyInstanceOf(SimpleDriverDataSource.class);
assertThat(bean).isNotNull();
assertThat(bean.getClass()).isEqualTo(SimpleDriverDataSource.class);
};
} }
@Test @Test
public void testExplicitDriverClassClearsUsername() throws Exception { public void testExplicitDriverClassClearsUsername() throws Exception {
this.contextLoader.env( this.context.withPropertyValues(
"spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), "spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(),
"spring.datasource.url:jdbc:foo://localhost").load(context -> { "spring.datasource.url:jdbc:foo://localhost").run((loaded) -> {
DataSource dataSource = context.getBean(DataSource.class); assertThat(loaded).hasSingleBean(DataSource.class);
assertThat(dataSource).isNotNull(); HikariDataSource dataSource = loaded.getBean(HikariDataSource.class);
assertThat(((HikariDataSource) dataSource).getDriverClassName()) assertThat(dataSource.getDriverClassName())
.isEqualTo(DatabaseTestDriver.class.getName()); .isEqualTo(DatabaseTestDriver.class.getName());
assertThat(((HikariDataSource) dataSource).getUsername()).isNull(); assertThat(dataSource.getUsername()).isNull();
}); });
} }
@Test @Test
public void testDefaultDataSourceCanBeOverridden() throws Exception { public void testDefaultDataSourceCanBeOverridden() throws Exception {
this.contextLoader.config(TestDataSourceConfiguration.class).load(context -> { this.context.withUserConfiguration(TestDataSourceConfiguration.class)
DataSource dataSource = context.getBean(DataSource.class); .run((loaded) -> {
assertThat(dataSource).isInstanceOf(BasicDataSource.class); assertThat(loaded).getBean(DataSource.class)
}); .isInstanceOf(BasicDataSource.class);
});
} }
@Test @Test
public void testDataSourceIsInitializedEarly() { public void testDataSourceIsInitializedEarly() {
this.contextLoader.config(TestInitializedDataSourceConfiguration.class) this.context.withUserConfiguration(TestInitializedDataSourceConfiguration.class)
.env("spring.datasource.initialize=true") .withPropertyValues("spring.datasource.initialize=true")
.load(context -> assertThat(context .run((loaded) -> assertThat(loaded
.getBean(TestInitializedDataSourceConfiguration.class).called) .getBean(TestInitializedDataSourceConfiguration.class).called)
.isTrue()); .isTrue());
} }
@ -227,8 +235,8 @@ public class DataSourceAutoConfigurationTests {
List<String> hiddenPackages, Consumer<T> consumer) { List<String> hiddenPackages, Consumer<T> consumer) {
HidePackagesClassLoader classLoader = new HidePackagesClassLoader( HidePackagesClassLoader classLoader = new HidePackagesClassLoader(
hiddenPackages.toArray(new String[hiddenPackages.size()])); hiddenPackages.toArray(new String[hiddenPackages.size()]));
this.contextLoader.classLoader(classLoader).load(context -> { this.context.withClassLoader(classLoader).run((loaded) -> {
DataSource bean = context.getBean(DataSource.class); DataSource bean = loaded.getBean(DataSource.class);
assertThat(bean).isInstanceOf(expectedType); assertThat(bean).isInstanceOf(expectedType);
consumer.accept(expectedType.cast(bean)); consumer.accept(expectedType.cast(bean));
}); });

View File

@ -26,8 +26,10 @@ import org.junit.Test;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.config.BeanPostProcessor; 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.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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
@ -61,229 +63,213 @@ public class JmsAutoConfigurationTests {
private static final String ACTIVEMQ_NETWORK_URL = "tcp://localhost:61616"; private static final String ACTIVEMQ_NETWORK_URL = "tcp://localhost:61616";
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class,
JmsAutoConfiguration.class));
@Test @Test
public void testDefaultJmsConfiguration() { public void testDefaultJmsConfiguration() {
this.contextLoader.config(TestConfiguration.class).load(context -> { this.context.withUserConfiguration(TestConfiguration.class)
ActiveMQConnectionFactory connectionFactory = context .run(this::testDefaultJmsConfiguration);
.getBean(ActiveMQConnectionFactory.class); }
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
JmsMessagingTemplate messagingTemplate = context private void testDefaultJmsConfiguration(AssertableApplicationContext loaded) {
.getBean(JmsMessagingTemplate.class); ActiveMQConnectionFactory factory = loaded
assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); .getBean(ActiveMQConnectionFactory.class);
assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) JmsMessagingTemplate messagingTemplate = loaded
.getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); .getBean(JmsMessagingTemplate.class);
assertThat(context.containsBean("jmsListenerContainerFactory")).isTrue(); 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 @Test
public void testConnectionFactoryBackOff() { public void testConnectionFactoryBackOff() {
this.contextLoader.config(TestConfiguration2.class) this.context.withUserConfiguration(TestConfiguration2.class)
.load(context -> assertThat( .run((loaded) -> assertThat(
context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL())
.isEqualTo("foobar")); .isEqualTo("foobar"));
} }
@Test @Test
public void testJmsTemplateBackOff() { public void testJmsTemplateBackOff() {
this.contextLoader.config(TestConfiguration3.class).load(context -> { this.context.withUserConfiguration(TestConfiguration3.class).run(
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); (loaded) -> assertThat(loaded.getBean(JmsTemplate.class).getPriority())
assertThat(jmsTemplate.getPriority()).isEqualTo(999); .isEqualTo(999));
});
} }
@Test @Test
public void testJmsMessagingTemplateBackOff() { public void testJmsMessagingTemplateBackOff() {
this.contextLoader.config(TestConfiguration5.class).load(context -> { this.context.withUserConfiguration(TestConfiguration5.class)
JmsMessagingTemplate messagingTemplate = context .run((loaded) -> assertThat(loaded.getBean(JmsMessagingTemplate.class)
.getBean(JmsMessagingTemplate.class); .getDefaultDestinationName()).isEqualTo("fooBar"));
assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar");
});
} }
@Test @Test
public void testJmsTemplateBackOffEverything() { public void testJmsTemplateBackOffEverything() {
this.contextLoader.config(TestConfiguration2.class, TestConfiguration3.class, this.context
TestConfiguration5.class).load(context -> { .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class,
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); TestConfiguration5.class)
assertThat(jmsTemplate.getPriority()).isEqualTo(999); .run(this::testJmsTemplateBackOffEverything);
assertThat(context.getBean(ActiveMQConnectionFactory.class) }
.getBrokerURL()).isEqualTo("foobar");
JmsMessagingTemplate messagingTemplate = context private void testJmsTemplateBackOffEverything(AssertableApplicationContext loaded) {
.getBean(JmsMessagingTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
assertThat(messagingTemplate.getDefaultDestinationName()) assertThat(jmsTemplate.getPriority()).isEqualTo(999);
.isEqualTo("fooBar"); assertThat(loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL())
assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); .isEqualTo("foobar");
}); JmsMessagingTemplate messagingTemplate = loaded
.getBean(JmsMessagingTemplate.class);
assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar");
assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate);
} }
@Test @Test
public void testEnableJmsCreateDefaultContainerFactory() { public void testEnableJmsCreateDefaultContainerFactory() {
this.contextLoader.config(EnableJmsConfiguration.class).load(context -> { this.context.withUserConfiguration(EnableJmsConfiguration.class)
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context.getBean( .run((loaded) -> assertThat(loaded)
"jmsListenerContainerFactory", JmsListenerContainerFactory.class); .getBean("jmsListenerContainerFactory",
assertThat(jmsListenerContainerFactory.getClass()) JmsListenerContainerFactory.class)
.isEqualTo(DefaultJmsListenerContainerFactory.class); .isExactlyInstanceOf(DefaultJmsListenerContainerFactory.class));
});
} }
@Test @Test
public void testJmsListenerContainerFactoryBackOff() { public void testJmsListenerContainerFactoryBackOff() {
this.contextLoader.config(TestConfiguration6.class, EnableJmsConfiguration.class) this.context
.load(context -> { .withUserConfiguration(TestConfiguration6.class,
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context EnableJmsConfiguration.class)
.getBean("jmsListenerContainerFactory", .run((loaded) -> assertThat(loaded)
JmsListenerContainerFactory.class); .getBean("jmsListenerContainerFactory",
assertThat(jmsListenerContainerFactory.getClass()) JmsListenerContainerFactory.class)
.isEqualTo(SimpleJmsListenerContainerFactory.class); .isExactlyInstanceOf(SimpleJmsListenerContainerFactory.class));
});
} }
@Test @Test
public void testJmsListenerContainerFactoryWithCustomSettings() { public void testJmsListenerContainerFactoryWithCustomSettings() {
this.contextLoader.config(EnableJmsConfiguration.class) this.context.withUserConfiguration(EnableJmsConfiguration.class)
.env("spring.jms.listener.autoStartup=false", .withPropertyValues("spring.jms.listener.autoStartup=false",
"spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.acknowledgeMode=client",
"spring.jms.listener.concurrency=2", "spring.jms.listener.concurrency=2",
"spring.jms.listener.maxConcurrency=10") "spring.jms.listener.maxConcurrency=10")
.load(context -> { .run(this::testJmsListenerContainerFactoryWithCustomSettings);
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context }
.getBean("jmsListenerContainerFactory",
JmsListenerContainerFactory.class); private void testJmsListenerContainerFactoryWithCustomSettings(
assertThat(jmsListenerContainerFactory.getClass()) AssertableApplicationContext loaded) {
.isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer container = getContainer(loaded,
DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) "jmsListenerContainerFactory");
.createListenerContainer(mock(JmsListenerEndpoint.class)); assertThat(container.isAutoStartup()).isFalse();
assertThat(listenerContainer.isAutoStartup()).isFalse(); assertThat(container.getSessionAcknowledgeMode())
assertThat(listenerContainer.getSessionAcknowledgeMode()) .isEqualTo(Session.CLIENT_ACKNOWLEDGE);
.isEqualTo(Session.CLIENT_ACKNOWLEDGE); assertThat(container.getConcurrentConsumers()).isEqualTo(2);
assertThat(listenerContainer.getConcurrentConsumers()).isEqualTo(2); assertThat(container.getMaxConcurrentConsumers());
assertThat(listenerContainer.getMaxConcurrentConsumers())
.isEqualTo(10);
});
} }
@Test @Test
public void testDefaultContainerFactoryWithJtaTransactionManager() { public void testDefaultContainerFactoryWithJtaTransactionManager() {
this.contextLoader.config(TestConfiguration7.class, EnableJmsConfiguration.class) this.context.withUserConfiguration(TestConfiguration7.class,
.load(context -> { EnableJmsConfiguration.class).run((loaded) -> {
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context DefaultMessageListenerContainer container = getContainer(loaded,
.getBean("jmsListenerContainerFactory", "jmsListenerContainerFactory");
JmsListenerContainerFactory.class); assertThat(container.isSessionTransacted()).isFalse();
assertThat(jmsListenerContainerFactory.getClass()) assertThat(new DirectFieldAccessor(container)
.isEqualTo(DefaultJmsListenerContainerFactory.class);
DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory)
.createListenerContainer(mock(JmsListenerEndpoint.class));
assertThat(listenerContainer.isSessionTransacted()).isFalse();
assertThat(new DirectFieldAccessor(listenerContainer)
.getPropertyValue("transactionManager")).isSameAs( .getPropertyValue("transactionManager")).isSameAs(
context.getBean(JtaTransactionManager.class)); loaded.getBean(JtaTransactionManager.class));
}); });
} }
@Test @Test
public void testDefaultContainerFactoryNonJtaTransactionManager() { public void testDefaultContainerFactoryNonJtaTransactionManager() {
this.contextLoader.config(TestConfiguration8.class, EnableJmsConfiguration.class) this.context.withUserConfiguration(TestConfiguration8.class,
.load(context -> { EnableJmsConfiguration.class).run((loaded) -> {
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context DefaultMessageListenerContainer container = getContainer(loaded,
.getBean("jmsListenerContainerFactory", "jmsListenerContainerFactory");
JmsListenerContainerFactory.class); assertThat(container.isSessionTransacted()).isTrue();
assertThat(jmsListenerContainerFactory.getClass()) assertThat(new DirectFieldAccessor(container)
.isEqualTo(DefaultJmsListenerContainerFactory.class);
DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory)
.createListenerContainer(mock(JmsListenerEndpoint.class));
assertThat(listenerContainer.isSessionTransacted()).isTrue();
assertThat(new DirectFieldAccessor(listenerContainer)
.getPropertyValue("transactionManager")).isNull(); .getPropertyValue("transactionManager")).isNull();
}); });
} }
@Test @Test
public void testDefaultContainerFactoryNoTransactionManager() { public void testDefaultContainerFactoryNoTransactionManager() {
this.contextLoader.config(EnableJmsConfiguration.class).load(context -> { this.context.withUserConfiguration(EnableJmsConfiguration.class).run((loaded) -> {
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context.getBean( DefaultMessageListenerContainer container = getContainer(loaded,
"jmsListenerContainerFactory", JmsListenerContainerFactory.class); "jmsListenerContainerFactory");
assertThat(jmsListenerContainerFactory.getClass()) assertThat(container.isSessionTransacted()).isTrue();
.isEqualTo(DefaultJmsListenerContainerFactory.class); assertThat(new DirectFieldAccessor(container)
DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory)
.createListenerContainer(mock(JmsListenerEndpoint.class));
assertThat(listenerContainer.isSessionTransacted()).isTrue();
assertThat(new DirectFieldAccessor(listenerContainer)
.getPropertyValue("transactionManager")).isNull(); .getPropertyValue("transactionManager")).isNull();
}); });
} }
@Test @Test
public void testDefaultContainerFactoryWithMessageConverters() { public void testDefaultContainerFactoryWithMessageConverters() {
this.contextLoader.config(MessageConvertersConfiguration.class, this.context.withUserConfiguration(MessageConvertersConfiguration.class,
EnableJmsConfiguration.class).load(context -> { EnableJmsConfiguration.class).run((loaded) -> {
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context DefaultMessageListenerContainer container = getContainer(loaded,
.getBean("jmsListenerContainerFactory", "jmsListenerContainerFactory");
JmsListenerContainerFactory.class); assertThat(container.getMessageConverter())
assertThat(jmsListenerContainerFactory.getClass()) .isSameAs(loaded.getBean("myMessageConverter"));
.isEqualTo(DefaultJmsListenerContainerFactory.class);
DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory)
.createListenerContainer(mock(JmsListenerEndpoint.class));
assertThat(listenerContainer.getMessageConverter())
.isSameAs(context.getBean("myMessageConverter"));
}); });
} }
@Test @Test
public void testCustomContainerFactoryWithConfigurer() { public void testCustomContainerFactoryWithConfigurer() {
this.contextLoader.config(TestConfiguration9.class, EnableJmsConfiguration.class) this.context
.env("spring.jms.listener.autoStartup=false").load(context -> { .withUserConfiguration(TestConfiguration9.class,
assertThat(context.containsBean("jmsListenerContainerFactory")) EnableJmsConfiguration.class)
.isTrue(); .withPropertyValues("spring.jms.listener.autoStartup=false")
JmsListenerContainerFactory<?> jmsListenerContainerFactory = context .run((loaded) -> {
.getBean("customListenerContainerFactory", DefaultMessageListenerContainer container = getContainer(loaded,
JmsListenerContainerFactory.class); "customListenerContainerFactory");
assertThat(jmsListenerContainerFactory) assertThat(container.getCacheLevel())
.isInstanceOf(DefaultJmsListenerContainerFactory.class);
DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory)
.createListenerContainer(mock(JmsListenerEndpoint.class));
assertThat(listenerContainer.getCacheLevel())
.isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); .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 @Test
public void testJmsTemplateWithMessageConverter() { public void testJmsTemplateWithMessageConverter() {
this.contextLoader.config(MessageConvertersConfiguration.class).load(context -> { this.context.withUserConfiguration(MessageConvertersConfiguration.class)
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); .run((loaded) -> {
assertThat(jmsTemplate.getMessageConverter()) JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
.isSameAs(context.getBean("myMessageConverter")); 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"));
}); });
} }
@Test
public void testJmsTemplateWithDestinationResolver() {
this.context.withUserConfiguration(DestinationResolversConfiguration.class)
.run((loaded) -> assertThat(
loaded.getBean(JmsTemplate.class).getDestinationResolver())
.isSameAs(loaded.getBean("myDestinationResolver")));
}
@Test @Test
public void testJmsTemplateFullCustomization() { public void testJmsTemplateFullCustomization() {
this.contextLoader.config(MessageConvertersConfiguration.class) this.context.withUserConfiguration(MessageConvertersConfiguration.class)
.env("spring.jms.template.default-destination=testQueue", .withPropertyValues("spring.jms.template.default-destination=testQueue",
"spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-delay=500",
"spring.jms.template.delivery-mode=non-persistent", "spring.jms.template.delivery-mode=non-persistent",
"spring.jms.template.priority=6", "spring.jms.template.priority=6",
"spring.jms.template.time-to-live=6000", "spring.jms.template.time-to-live=6000",
"spring.jms.template.receive-timeout=2000") "spring.jms.template.receive-timeout=2000")
.load(context -> { .run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
assertThat(jmsTemplate.getMessageConverter()) assertThat(jmsTemplate.getMessageConverter())
.isSameAs(context.getBean("myMessageConverter")); .isSameAs(loaded.getBean("myMessageConverter"));
assertThat(jmsTemplate.isPubSubDomain()).isFalse(); assertThat(jmsTemplate.isPubSubDomain()).isFalse();
assertThat(jmsTemplate.getDefaultDestinationName()) assertThat(jmsTemplate.getDefaultDestinationName())
.isEqualTo("testQueue"); .isEqualTo("testQueue");
@ -298,26 +284,24 @@ public class JmsAutoConfigurationTests {
@Test @Test
public void testPubSubDisabledByDefault() { public void testPubSubDisabledByDefault() {
this.contextLoader.config(TestConfiguration.class).load(context -> { this.context.withUserConfiguration(TestConfiguration.class).run(
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); (loaded) -> assertThat(loaded.getBean(JmsTemplate.class).isPubSubDomain())
assertThat(jmsTemplate.isPubSubDomain()).isFalse(); .isFalse());
});
} }
@Test @Test
public void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { public void testJmsTemplatePostProcessedSoThatPubSubIsTrue() {
this.contextLoader.config(TestConfiguration4.class).load(context -> { this.context.withUserConfiguration(TestConfiguration4.class).run(
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); (loaded) -> assertThat(loaded.getBean(JmsTemplate.class).isPubSubDomain())
assertThat(jmsTemplate.isPubSubDomain()).isTrue(); .isTrue());
});
} }
@Test @Test
public void testPubSubDomainActive() { public void testPubSubDomainActive() {
this.contextLoader.config(TestConfiguration.class) this.context.withUserConfiguration(TestConfiguration.class)
.env("spring.jms.pubSubDomain:true").load(context -> { .withPropertyValues("spring.jms.pubSubDomain:true").run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
DefaultMessageListenerContainer defaultMessageListenerContainer = context DefaultMessageListenerContainer defaultMessageListenerContainer = loaded
.getBean(DefaultJmsListenerContainerFactory.class) .getBean(DefaultJmsListenerContainerFactory.class)
.createListenerContainer(mock(JmsListenerEndpoint.class)); .createListenerContainer(mock(JmsListenerEndpoint.class));
assertThat(jmsTemplate.isPubSubDomain()).isTrue(); assertThat(jmsTemplate.isPubSubDomain()).isTrue();
@ -327,29 +311,27 @@ public class JmsAutoConfigurationTests {
@Test @Test
public void testPubSubDomainOverride() { public void testPubSubDomainOverride() {
this.contextLoader.config(TestConfiguration.class) this.context.withUserConfiguration(TestConfiguration.class)
.env("spring.jms.pubSubDomain:false").load(context -> { .withPropertyValues("spring.jms.pubSubDomain:false").run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate).isNotNull();
assertThat(jmsTemplate.isPubSubDomain()).isFalse(); assertThat(jmsTemplate.isPubSubDomain()).isFalse();
assertThat(connectionFactory).isNotNull(); assertThat(factory).isNotNull()
assertThat(connectionFactory)
.isEqualTo(jmsTemplate.getConnectionFactory()); .isEqualTo(jmsTemplate.getConnectionFactory());
}); });
} }
@Test @Test
public void testActiveMQOverriddenStandalone() { public void testActiveMQOverriddenStandalone() {
this.contextLoader.config(TestConfiguration.class) this.context.withUserConfiguration(TestConfiguration.class)
.env("spring.activemq.inMemory:false").load(context -> { .withPropertyValues("spring.activemq.inMemory:false").run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate).isNotNull();
assertThat(connectionFactory).isNotNull(); assertThat(factory).isNotNull()
assertThat(connectionFactory)
.isEqualTo(jmsTemplate.getConnectionFactory()); .isEqualTo(jmsTemplate.getConnectionFactory());
assertThat(((ActiveMQConnectionFactory) jmsTemplate assertThat(((ActiveMQConnectionFactory) jmsTemplate
.getConnectionFactory()).getBrokerURL()) .getConnectionFactory()).getBrokerURL())
@ -359,16 +341,15 @@ public class JmsAutoConfigurationTests {
@Test @Test
public void testActiveMQOverriddenRemoteHost() { public void testActiveMQOverriddenRemoteHost() {
this.contextLoader.config(TestConfiguration.class) this.context.withUserConfiguration(TestConfiguration.class)
.env("spring.activemq.brokerUrl:tcp://remote-host:10000") .withPropertyValues("spring.activemq.brokerUrl:tcp://remote-host:10000")
.load(context -> { .run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate).isNotNull();
assertThat(connectionFactory).isNotNull(); assertThat(factory).isNotNull();
assertThat(connectionFactory) assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory());
.isEqualTo(jmsTemplate.getConnectionFactory());
assertThat(((ActiveMQConnectionFactory) jmsTemplate assertThat(((ActiveMQConnectionFactory) jmsTemplate
.getConnectionFactory()).getBrokerURL()) .getConnectionFactory()).getBrokerURL())
.isEqualTo("tcp://remote-host:10000"); .isEqualTo("tcp://remote-host:10000");
@ -377,10 +358,10 @@ public class JmsAutoConfigurationTests {
@Test @Test
public void testActiveMQOverriddenPool() { public void testActiveMQOverriddenPool() {
this.contextLoader.config(TestConfiguration.class) this.context.withUserConfiguration(TestConfiguration.class)
.env("spring.activemq.pool.enabled:true").load(context -> { .withPropertyValues("spring.activemq.pool.enabled:true").run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
PooledConnectionFactory pool = context PooledConnectionFactory pool = loaded
.getBean(PooledConnectionFactory.class); .getBean(PooledConnectionFactory.class);
assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate).isNotNull();
assertThat(pool).isNotNull(); assertThat(pool).isNotNull();
@ -393,12 +374,12 @@ public class JmsAutoConfigurationTests {
@Test @Test
public void testActiveMQOverriddenPoolAndStandalone() { public void testActiveMQOverriddenPoolAndStandalone() {
this.contextLoader.config(TestConfiguration.class) this.context.withUserConfiguration(TestConfiguration.class)
.env("spring.activemq.pool.enabled:true", .withPropertyValues("spring.activemq.pool.enabled:true",
"spring.activemq.inMemory:false") "spring.activemq.inMemory:false")
.load(context -> { .run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
PooledConnectionFactory pool = context PooledConnectionFactory pool = loaded
.getBean(PooledConnectionFactory.class); .getBean(PooledConnectionFactory.class);
assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate).isNotNull();
assertThat(pool).isNotNull(); assertThat(pool).isNotNull();
@ -411,12 +392,12 @@ public class JmsAutoConfigurationTests {
@Test @Test
public void testActiveMQOverriddenPoolAndRemoteServer() { public void testActiveMQOverriddenPoolAndRemoteServer() {
this.contextLoader.config(TestConfiguration.class) this.context.withUserConfiguration(TestConfiguration.class)
.env("spring.activemq.pool.enabled:true", .withPropertyValues("spring.activemq.pool.enabled:true",
"spring.activemq.brokerUrl:tcp://remote-host:10000") "spring.activemq.brokerUrl:tcp://remote-host:10000")
.load(context -> { .run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
PooledConnectionFactory pool = context PooledConnectionFactory pool = loaded
.getBean(PooledConnectionFactory.class); .getBean(PooledConnectionFactory.class);
assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate).isNotNull();
assertThat(pool).isNotNull(); assertThat(pool).isNotNull();
@ -430,12 +411,14 @@ public class JmsAutoConfigurationTests {
@Test @Test
public void enableJmsAutomatically() throws Exception { public void enableJmsAutomatically() throws Exception {
this.contextLoader.config(NoEnableJmsConfiguration.class).load(context -> { this.context.withUserConfiguration(NoEnableJmsConfiguration.class)
context.getBean( .run((loaded) -> {
JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); assertThat(loaded)
context.getBean( .hasBean(
JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
}); .hasBean(
JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME);
});
} }
@Configuration @Configuration

View File

@ -23,8 +23,9 @@ import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory; import org.apache.activemq.pool.PooledConnectionFactory;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration; 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -41,67 +42,59 @@ import static org.mockito.Mockito.mockingDetails;
*/ */
public class ActiveMQAutoConfigurationTests { public class ActiveMQAutoConfigurationTests {
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(ActiveMQAutoConfiguration.class, JmsAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class,
JmsAutoConfiguration.class));
@Test @Test
public void brokerIsEmbeddedByDefault() { public void brokerIsEmbeddedByDefault() {
this.contextLoader.config(EmptyConfiguration.class).load(context -> { this.context.withUserConfiguration(EmptyConfiguration.class).run((loaded) -> {
ConnectionFactory connectionFactory = context assertThat(loaded).getBean(ConnectionFactory.class)
.getBean(ConnectionFactory.class); .isInstanceOf(ActiveMQConnectionFactory.class);
assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); assertThat(loaded.getBean(ActiveMQConnectionFactory.class).getBrokerURL())
String brokerUrl = ((ActiveMQConnectionFactory) connectionFactory) .isEqualTo("vm://localhost?broker.persistent=false");
.getBrokerURL();
assertThat(brokerUrl).isEqualTo("vm://localhost?broker.persistent=false");
}); });
} }
@Test @Test
public void configurationBacksOffWhenCustomConnectionFactoryExists() { public void configurationBacksOffWhenCustomConnectionFactoryExists() {
this.contextLoader.config(CustomConnectionFactoryConfiguration.class) this.context.withUserConfiguration(CustomConnectionFactoryConfiguration.class)
.load(context -> assertThat( .run((loaded) -> assertThat(
mockingDetails(context.getBean(ConnectionFactory.class)).isMock()) mockingDetails(loaded.getBean(ConnectionFactory.class)).isMock())
.isTrue()); .isTrue());
} }
@Test @Test
public void customPooledConnectionFactoryConfiguration() { public void customPooledConnectionFactoryConfiguration() {
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.activemq.pool.enabled:true", .withPropertyValues("spring.activemq.pool.enabled:true",
"spring.activemq.pool.maxConnections:256", "spring.activemq.pool.maxConnections:256",
"spring.activemq.pool.idleTimeout:512", "spring.activemq.pool.idleTimeout:512",
"spring.activemq.pool.expiryTimeout:4096", "spring.activemq.pool.expiryTimeout:4096",
"spring.activemq.pool.configuration.maximumActiveSessionPerConnection:1024", "spring.activemq.pool.configuration.maximumActiveSessionPerConnection:1024",
"spring.activemq.pool.configuration.timeBetweenExpirationCheckMillis:2048") "spring.activemq.pool.configuration.timeBetweenExpirationCheckMillis:2048")
.load(context -> { .run((loaded) -> {
ConnectionFactory connectionFactory = context ConnectionFactory factory = loaded.getBean(ConnectionFactory.class);
.getBean(ConnectionFactory.class); assertThat(factory).isInstanceOf(PooledConnectionFactory.class);
assertThat(connectionFactory) PooledConnectionFactory pooledFactory = (PooledConnectionFactory) factory;
.isInstanceOf(PooledConnectionFactory.class); assertThat(pooledFactory.getMaxConnections()).isEqualTo(256);
PooledConnectionFactory pooledConnectionFactory = (PooledConnectionFactory) connectionFactory; assertThat(pooledFactory.getIdleTimeout()).isEqualTo(512);
assertThat(pooledConnectionFactory.getMaxConnections()) assertThat(pooledFactory.getMaximumActiveSessionPerConnection())
.isEqualTo(256); .isEqualTo(1024);
assertThat(pooledConnectionFactory.getIdleTimeout()).isEqualTo(512); assertThat(pooledFactory.getTimeBetweenExpirationCheckMillis())
assertThat(pooledConnectionFactory .isEqualTo(2048);
.getMaximumActiveSessionPerConnection()).isEqualTo(1024); assertThat(pooledFactory.getExpiryTimeout()).isEqualTo(4096);
assertThat(
pooledConnectionFactory.getTimeBetweenExpirationCheckMillis())
.isEqualTo(2048);
assertThat(pooledConnectionFactory.getExpiryTimeout())
.isEqualTo(4096);
}); });
} }
@Test @Test
public void pooledConnectionFactoryConfiguration() throws JMSException { public void pooledConnectionFactoryConfiguration() throws JMSException {
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.activemq.pool.enabled:true").load(context -> { .withPropertyValues("spring.activemq.pool.enabled:true").run((loaded) -> {
ConnectionFactory connectionFactory = context ConnectionFactory factory = loaded.getBean(ConnectionFactory.class);
.getBean(ConnectionFactory.class); assertThat(factory).isInstanceOf(PooledConnectionFactory.class);
assertThat(connectionFactory) loaded.getSourceApplicationContext().close();
.isInstanceOf(PooledConnectionFactory.class); assertThat(factory.createConnection()).isNull();
context.close();
assertThat(connectionFactory.createConnection()).isNull();
}); });
} }

View File

@ -41,13 +41,13 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration; 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.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.SessionCallback; import org.springframework.jms.core.SessionCallback;
import org.springframework.jms.support.destination.DestinationResolver; import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.jms.support.destination.DynamicDestinationResolver; import org.springframework.jms.support.destination.DynamicDestinationResolver;
@ -65,110 +65,108 @@ public class ArtemisAutoConfigurationTests {
@Rule @Rule
public final TemporaryFolder folder = new TemporaryFolder(); public final TemporaryFolder folder = new TemporaryFolder();
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class,
JmsAutoConfiguration.class));
@Test @Test
public void nativeConnectionFactory() { public void nativeConnectionFactory() {
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.artemis.mode:native").load(context -> { .withPropertyValues("spring.artemis.mode:native").run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertThat(connectionFactory) assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory());
.isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(factory, "localhost", 61616);
assertNettyConnectionFactory(connectionFactory, "localhost", 61616); assertThat(factory.getUser()).isNull();
assertThat(connectionFactory.getUser()).isNull(); assertThat(factory.getPassword()).isNull();
assertThat(connectionFactory.getPassword()).isNull();
}); });
} }
@Test @Test
public void nativeConnectionFactoryCustomHost() { public void nativeConnectionFactoryCustomHost() {
this.contextLoader this.context.withUserConfiguration(EmptyConfiguration.class)
.config(EmptyConfiguration.class).env("spring.artemis.mode:native", .withPropertyValues("spring.artemis.mode:native",
"spring.artemis.host:192.168.1.144", "spring.artemis.port:9876") "spring.artemis.host:192.168.1.144", "spring.artemis.port:9876")
.load(context -> { .run((loaded) -> {
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertNettyConnectionFactory(connectionFactory, "192.168.1.144", assertNettyConnectionFactory(factory, "192.168.1.144", 9876);
9876);
}); });
} }
@Test @Test
public void nativeConnectionFactoryCredentials() { public void nativeConnectionFactoryCredentials() {
this.contextLoader this.context.withUserConfiguration(EmptyConfiguration.class)
.config(EmptyConfiguration.class).env("spring.artemis.mode:native", .withPropertyValues("spring.artemis.mode:native",
"spring.artemis.user:user", "spring.artemis.password:secret") "spring.artemis.user:user", "spring.artemis.password:secret")
.load(context -> { .run((loaded) -> {
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); JmsTemplate jmsTemplate = loaded.getBean(JmsTemplate.class);
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertThat(connectionFactory) assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory());
.isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(factory, "localhost", 61616);
assertNettyConnectionFactory(connectionFactory, "localhost", 61616); assertThat(factory.getUser()).isEqualTo("user");
assertThat(connectionFactory.getUser()).isEqualTo("user"); assertThat(factory.getPassword()).isEqualTo("secret");
assertThat(connectionFactory.getPassword()).isEqualTo("secret");
}); });
} }
@Test @Test
public void embeddedConnectionFactory() { public void embeddedConnectionFactory() {
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.artemis.mode:embedded").load(context -> { .withPropertyValues("spring.artemis.mode:embedded").run((loaded) -> {
ArtemisProperties properties = context ArtemisProperties properties = loaded
.getBean(ArtemisProperties.class); .getBean(ArtemisProperties.class);
assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED);
assertThat(context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); assertThat(loaded).hasSingleBean(EmbeddedJMS.class);
org.apache.activemq.artemis.core.config.Configuration configuration = context org.apache.activemq.artemis.core.config.Configuration configuration = loaded
.getBean( .getBean(
org.apache.activemq.artemis.core.config.Configuration.class); org.apache.activemq.artemis.core.config.Configuration.class);
assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isPersistenceEnabled()).isFalse();
assertThat(configuration.isSecurityEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse();
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertInVmConnectionFactory(connectionFactory); assertInVmConnectionFactory(factory);
}); });
} }
@Test @Test
public void embeddedConnectionFactoryByDefault() { public void embeddedConnectionFactoryByDefault() {
// No mode is specified // No mode is specified
this.contextLoader.config(EmptyConfiguration.class).load(context -> { this.context.withUserConfiguration(EmptyConfiguration.class).run((loaded) -> {
assertThat(context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); assertThat(loaded).hasSingleBean(EmbeddedJMS.class);
org.apache.activemq.artemis.core.config.Configuration configuration = context org.apache.activemq.artemis.core.config.Configuration configuration = loaded
.getBean(org.apache.activemq.artemis.core.config.Configuration.class); .getBean(org.apache.activemq.artemis.core.config.Configuration.class);
assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isPersistenceEnabled()).isFalse();
assertThat(configuration.isSecurityEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse();
ActiveMQConnectionFactory factory = loaded
ActiveMQConnectionFactory connectionFactory = context
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertInVmConnectionFactory(connectionFactory); assertInVmConnectionFactory(factory);
}); });
} }
@Test @Test
public void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { public void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() {
// No mode is specified // No mode is specified
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.artemis.embedded.enabled:false").load(context -> { .withPropertyValues("spring.artemis.embedded.enabled:false")
assertThat(context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); .run((loaded) -> {
ActiveMQConnectionFactory connectionFactory = context assertThat(loaded).doesNotHaveBean(EmbeddedJMS.class);
ActiveMQConnectionFactory factory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertNettyConnectionFactory(connectionFactory, "localhost", 61616); assertNettyConnectionFactory(factory, "localhost", 61616);
}); });
} }
@Test @Test
public void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { public void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() {
// No mode is specified // No mode is specified
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.artemis.mode:embedded", .withPropertyValues("spring.artemis.mode:embedded",
"spring.artemis.embedded.enabled:false") "spring.artemis.embedded.enabled:false")
.load(context -> { .run((loaded) -> {
assertThat(context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); assertThat(loaded.getBeansOfType(EmbeddedJMS.class)).isEmpty();
ActiveMQConnectionFactory connectionFactory = context ActiveMQConnectionFactory connectionFactory = loaded
.getBean(ActiveMQConnectionFactory.class); .getBean(ActiveMQConnectionFactory.class);
assertInVmConnectionFactory(connectionFactory); assertInVmConnectionFactory(connectionFactory);
}); });
@ -176,11 +174,11 @@ public class ArtemisAutoConfigurationTests {
@Test @Test
public void embeddedServerWithDestinations() { public void embeddedServerWithDestinations() {
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.artemis.embedded.queues=Queue1,Queue2", .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2",
"spring.artemis.embedded.topics=Topic1") "spring.artemis.embedded.topics=Topic1")
.load(context -> { .run((loaded) -> {
DestinationChecker checker = new DestinationChecker(context); DestinationChecker checker = new DestinationChecker(loaded);
checker.checkQueue("Queue1", true); checker.checkQueue("Queue1", true);
checker.checkQueue("Queue2", true); checker.checkQueue("Queue2", true);
checker.checkQueue("QueueWillNotBeAutoCreated", true); checker.checkQueue("QueueWillNotBeAutoCreated", true);
@ -191,19 +189,21 @@ public class ArtemisAutoConfigurationTests {
@Test @Test
public void embeddedServerWithDestinationConfig() { public void embeddedServerWithDestinationConfig() {
this.contextLoader.config(DestinationConfiguration.class).load(context -> { this.context.withUserConfiguration(DestinationConfiguration.class)
DestinationChecker checker = new DestinationChecker(context); .run((loaded) -> {
checker.checkQueue("sampleQueue", true); DestinationChecker checker = new DestinationChecker(loaded);
checker.checkTopic("sampleTopic", true); checker.checkQueue("sampleQueue", true);
}); checker.checkTopic("sampleTopic", true);
});
} }
@Test @Test
public void embeddedServiceWithCustomJmsConfiguration() { public void embeddedServiceWithCustomJmsConfiguration() {
// Ignored with custom config // Ignored with custom config
this.contextLoader.config(CustomJmsConfiguration.class) this.context.withUserConfiguration(CustomJmsConfiguration.class)
.env("spring.artemis.embedded.queues=Queue1,Queue2").load(context -> { .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2")
DestinationChecker checker = new DestinationChecker(context); .run((loaded) -> {
DestinationChecker checker = new DestinationChecker(loaded);
checker.checkQueue("custom", true); // See CustomJmsConfiguration checker.checkQueue("custom", true); // See CustomJmsConfiguration
checker.checkQueue("Queue1", true); checker.checkQueue("Queue1", true);
checker.checkQueue("Queue2", true); checker.checkQueue("Queue2", true);
@ -212,94 +212,77 @@ public class ArtemisAutoConfigurationTests {
@Test @Test
public void embeddedServiceWithCustomArtemisConfiguration() { public void embeddedServiceWithCustomArtemisConfiguration() {
this.contextLoader.config(CustomArtemisConfiguration.class).load(context -> { this.context.withUserConfiguration(CustomArtemisConfiguration.class)
org.apache.activemq.artemis.core.config.Configuration configuration = context .run((loaded) -> assertThat(loaded
.getBean(org.apache.activemq.artemis.core.config.Configuration.class); .getBean(
assertThat(configuration.getName()).isEqualTo("customFooBar"); org.apache.activemq.artemis.core.config.Configuration.class)
}); .getName()).isEqualTo("customFooBar"));
} }
@Test @Test
public void embeddedWithPersistentMode() throws IOException, JMSException { public void embeddedWithPersistentMode() throws IOException, JMSException {
File dataFolder = this.folder.newFolder(); 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 // Start the server and post a message to some queue
this.contextLoader.config(EmptyConfiguration.class).env( this.context.withUserConfiguration(EmptyConfiguration.class)
"spring.artemis.embedded.queues=TestQueue", .withPropertyValues("spring.artemis.embedded.queues=TestQueue",
"spring.artemis.embedded.persistent:true", "spring.artemis.embedded.persistent:true",
"spring.artemis.embedded.dataDirectory:" + dataFolder.getAbsolutePath()) "spring.artemis.embedded.dataDirectory:"
.load(context -> { + dataFolder.getAbsolutePath())
.run((loaded) -> loaded.getBean(JmsTemplate.class).send("TestQueue",
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); (session) -> session.createTextMessage(messageId)));
jmsTemplate.send("TestQueue", new MessageCreator() {
@Override
public Message createMessage(Session session)
throws JMSException {
return session.createTextMessage(msgId);
}
});
});
// Start the server again and check if our message is still here // Start the server again and check if our message is still here
this.contextLoader.load(context -> { this.context.run((loaded) -> {
JmsTemplate jmsTemplate2 = loaded.getBean(JmsTemplate.class);
JmsTemplate jmsTemplate2 = context.getBean(JmsTemplate.class);
jmsTemplate2.setReceiveTimeout(1000L); jmsTemplate2.setReceiveTimeout(1000L);
Message message = jmsTemplate2.receive("TestQueue"); Message message = jmsTemplate2.receive("TestQueue");
assertThat(message).isNotNull(); assertThat(message).isNotNull();
assertThat(((TextMessage) message).getText()).isEqualTo(msgId); assertThat(((TextMessage) message).getText()).isEqualTo(messageId);
}); });
} }
@Test @Test
public void severalEmbeddedBrokers() { public void severalEmbeddedBrokers() {
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.artemis.embedded.queues=Queue1").load(rootContext -> { .withPropertyValues("spring.artemis.embedded.queues=Queue1")
this.contextLoader.env("spring.artemis.embedded.queues=Queue2") .run((first) -> {
.load(anotherContext -> { this.context
ArtemisProperties properties = rootContext .withPropertyValues("spring.artemis.embedded.queues=Queue2")
.run((second) -> {
ArtemisProperties firstProperties = first
.getBean(ArtemisProperties.class); .getBean(ArtemisProperties.class);
ArtemisProperties anotherProperties = anotherContext ArtemisProperties secondProperties = second
.getBean(ArtemisProperties.class); .getBean(ArtemisProperties.class);
assertThat( assertThat(firstProperties.getEmbedded().getServerId())
properties.getEmbedded().getServerId() < anotherProperties .isLessThan(secondProperties.getEmbedded().getServerId());
.getEmbedded().getServerId()).isTrue(); DestinationChecker firstChecker = new DestinationChecker(first);
DestinationChecker checker = new DestinationChecker( firstChecker.checkQueue("Queue1", true);
anotherContext); firstChecker.checkQueue("Queue2", true);
checker.checkQueue("Queue1", true); DestinationChecker secondChecker = new DestinationChecker(second);
checker.checkQueue("Queue2", true); secondChecker.checkQueue("Queue2", true);
DestinationChecker anotherChecker = new DestinationChecker( secondChecker.checkQueue("Queue1", true);
anotherContext);
anotherChecker.checkQueue("Queue2", true);
anotherChecker.checkQueue("Queue1", true);
}); });
}); });
} }
@Test @Test
public void connectToASpecificEmbeddedBroker() { public void connectToASpecificEmbeddedBroker() {
this.contextLoader.config(EmptyConfiguration.class) this.context.withUserConfiguration(EmptyConfiguration.class)
.env("spring.artemis.embedded.serverId=93", .withPropertyValues("spring.artemis.embedded.serverId=93",
"spring.artemis.embedded.queues=Queue1") "spring.artemis.embedded.queues=Queue1")
.load(context -> { .run((first) -> {
this.contextLoader.config(EmptyConfiguration.class).env( this.context.withUserConfiguration(EmptyConfiguration.class)
"spring.artemis.mode=embedded", .withPropertyValues("spring.artemis.mode=embedded",
"spring.artemis.embedded.serverId=93", /* // Connect to the "main" broker
* Connect to the "spring.artemis.embedded.serverId=93",
* "main" broker // Do not start a specific one
*/ "spring.artemis.embedded.enabled=false")
"spring.artemis.embedded.enabled=false" /* .run(secondContext -> {
* do not start a DestinationChecker firstChecker = new DestinationChecker(first);
* specific one firstChecker.checkQueue("Queue1", true);
*/) DestinationChecker secondChecker = new DestinationChecker(
.load(anotherContext -> { secondContext);
DestinationChecker checker = new DestinationChecker(context); secondChecker.checkQueue("Queue1", true);
checker.checkQueue("Queue1", true);
DestinationChecker anotherChecker = new DestinationChecker(
anotherContext);
anotherChecker.checkQueue("Queue1", true);
}); });
}); });
} }

View File

@ -18,8 +18,8 @@ package org.springframework.boot.autoconfigure.web.reactive;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.test.context.ContextLoader; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.ReactiveWebContextLoader; import org.springframework.boot.test.context.ReactiveWebApplicationContextTester;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.HttpHandler;
@ -39,23 +39,25 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class HttpHandlerAutoConfigurationTests { public class HttpHandlerAutoConfigurationTests {
private final ReactiveWebContextLoader contextLoader = ContextLoader.reactiveWeb() private final ReactiveWebApplicationContextTester context = new ReactiveWebApplicationContextTester()
.autoConfig(HttpHandlerAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class));
@Test @Test
public void shouldNotProcessIfExistingHttpHandler() { public void shouldNotProcessIfExistingHttpHandler() {
this.contextLoader.config(CustomHttpHandler.class).load(context -> { this.context.withUserConfiguration(CustomHttpHandler.class).run((loaded) -> {
assertThat(context.getBeansOfType(HttpHandler.class)).hasSize(1); assertThat(loaded).hasSingleBean(HttpHandler.class);
assertThat(context.getBean(HttpHandler.class)) assertThat(loaded).getBean(HttpHandler.class)
.isSameAs(context.getBean("customHttpHandler")); .isSameAs(loaded.getBean("customHttpHandler"));
}); });
} }
@Test @Test
public void shouldConfigureHttpHandlerAnnotation() { public void shouldConfigureHttpHandlerAnnotation() {
this.contextLoader.autoConfig(WebFluxAutoConfiguration.class).load(context -> { this.context
assertThat(context.getBeansOfType(HttpHandler.class).size()).isEqualTo(1); .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class))
}); .run((loaded) -> {
assertThat(loaded).hasSingleBean(HttpHandler.class);
});
} }
@Configuration @Configuration

View File

@ -16,14 +16,17 @@
package org.springframework.boot.autoconfigure.webservices; package org.springframework.boot.autoconfigure.webservices;
import java.util.Collection;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanCreationException; 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.ServletWebContextLoader; import org.springframework.boot.test.context.WebApplicationContextTester;
import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -37,52 +40,46 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class WebServicesAutoConfigurationTests { public class WebServicesAutoConfigurationTests {
private final ServletWebContextLoader contextLoader = ContextLoader.servletWeb() private final WebApplicationContextTester context = new WebApplicationContextTester()
.autoConfig(WebServicesAutoConfiguration.class); .withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class));
@Rule @Rule
public ExpectedException thrown = ExpectedException.none(); public ExpectedException thrown = ExpectedException.none();
@Test @Test
public void defaultConfiguration() { public void defaultConfiguration() {
this.contextLoader.load(context -> { this.context.run((loaded) -> assertThat(loaded)
assertThat(context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); .hasSingleBean(ServletRegistrationBean.class));
});
} }
@Test @Test
public void customPathMustBeginWithASlash() { public void customPathMustBeginWithASlash() {
this.contextLoader.env("spring.webservices.path=invalid") this.context.withPropertyValues("spring.webservices.path=invalid")
.loadAndFail(BeanCreationException.class, (ex) -> { .run((loaded) -> {
System.out.println(ex.getMessage()); assertThat(loaded).getFailure()
assertThat(ex.getMessage()).contains( .isInstanceOf(BeanCreationException.class)
"Failed to bind properties under 'spring.webservices'"); .hasMessageContaining(
"Failed to bind properties under 'spring.webservices'");
}); });
} }
@Test @Test
public void customPath() { public void customPath() {
this.contextLoader.env("spring.webservices.path=/valid").load(context -> { this.context.withPropertyValues("spring.webservices.path=/valid")
ServletRegistrationBean<?> servletRegistrationBean = context .run((loaded) -> assertThat(getUrlMappings(loaded)).contains("/valid/*"));
.getBean(ServletRegistrationBean.class);
assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*");
});
} }
@Test @Test
public void customPathWithTrailingSlash() { public void customPathWithTrailingSlash() {
this.contextLoader.env("spring.webservices.path=/valid/").load(context -> { this.context.withPropertyValues("spring.webservices.path=/valid/")
ServletRegistrationBean<?> servletRegistrationBean = context .run((loaded) -> assertThat(getUrlMappings(loaded)).contains("/valid/*"));
.getBean(ServletRegistrationBean.class);
assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*");
});
} }
@Test @Test
public void customLoadOnStartup() { public void customLoadOnStartup() {
this.contextLoader.env("spring.webservices.servlet.load-on-startup=1") this.context.withPropertyValues("spring.webservices.servlet.load-on-startup=1")
.load(context -> { .run((loaded) -> {
ServletRegistrationBean<?> registrationBean = context ServletRegistrationBean<?> registrationBean = loaded
.getBean(ServletRegistrationBean.class); .getBean(ServletRegistrationBean.class);
assertThat(ReflectionTestUtils.getField(registrationBean, assertThat(ReflectionTestUtils.getField(registrationBean,
"loadOnStartup")).isEqualTo(1); "loadOnStartup")).isEqualTo(1);
@ -91,15 +88,22 @@ public class WebServicesAutoConfigurationTests {
@Test @Test
public void customInitParameters() { public void customInitParameters() {
this.contextLoader.env("spring.webservices.servlet.init.key1=value1", this.context
"spring.webservices.servlet.init.key2=value2").load(context -> { .withPropertyValues("spring.webservices.servlet.init.key1=value1",
ServletRegistrationBean<?> registrationBean = context "spring.webservices.servlet.init.key2=value2")
.getBean(ServletRegistrationBean.class); .run(loaded -> assertThat(
assertThat(registrationBean.getInitParameters()).containsEntry("key1", getServletRegistrationBean(loaded).getInitParameters())
"value1"); .containsEntry("key1", "value1")
assertThat(registrationBean.getInitParameters()).containsEntry("key2", .containsEntry("key2", "value2"));
"value2"); }
});
private Collection<String> getUrlMappings(ApplicationContext loaded) {
return getServletRegistrationBean(loaded).getUrlMappings();
}
private ServletRegistrationBean<?> getServletRegistrationBean(
ApplicationContext loaded) {
return loaded.getBean(ServletRegistrationBean.class);
} }
} }

View File

@ -20,7 +20,8 @@ import javax.sql.DataSource;
import org.junit.Test; 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
@ -37,29 +38,32 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class TestDatabaseAutoConfigurationTests { public class TestDatabaseAutoConfigurationTests {
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.autoConfig(TestDatabaseAutoConfiguration.class); .withConfiguration(
AutoConfigurations.of(TestDatabaseAutoConfiguration.class));
@Test @Test
public void replaceWithNoDataSourceAvailable() { public void replaceWithNoDataSourceAvailable() {
this.contextLoader.load(context -> { this.context
assertThat(context.getBeansOfType(DataSource.class)).isEmpty(); .run((loaded) -> assertThat(loaded).doesNotHaveBean(DataSource.class));
});
} }
@Test @Test
public void replaceWithUniqueDatabase() { public void replaceWithUniqueDatabase() {
this.contextLoader.config(ExistingDataSourceConfiguration.class).load(context -> { this.context.withUserConfiguration(ExistingDataSourceConfiguration.class)
DataSource datasource = context.getBean(DataSource.class); .run((loaded) -> {
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); DataSource datasource = loaded.getBean(DataSource.class);
jdbcTemplate.execute("create table example (id int, name varchar);"); JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
this.contextLoader.load(anotherContext -> { jdbcTemplate.execute("create table example (id int, name varchar);");
DataSource anotherDatasource = anotherContext.getBean(DataSource.class); this.context.run((secondContext) -> {
JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource); DataSource anotherDatasource = secondContext
anotherJdbcTemplate .getBean(DataSource.class);
.execute("create table example (id int, name varchar);"); JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(
}); anotherDatasource);
}); anotherJdbcTemplate
.execute("create table example (id int, name varchar);");
});
});
} }
@Configuration @Configuration

View File

@ -22,8 +22,9 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanCreationException; 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.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.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -43,31 +44,32 @@ import static org.mockito.Mockito.mock;
@ClassPathExclusions({ "h2-*.jar", "hsqldb-*.jar", "derby-*.jar" }) @ClassPathExclusions({ "h2-*.jar", "hsqldb-*.jar", "derby-*.jar" })
public class TestDatabaseAutoConfigurationNoEmbeddedTests { public class TestDatabaseAutoConfigurationNoEmbeddedTests {
private final ContextLoader contextLoader = ContextLoader.standard() private final ApplicationContextTester context = new ApplicationContextTester()
.config(ExistingDataSourceConfiguration.class) .withUserConfiguration(ExistingDataSourceConfiguration.class)
.autoConfig(TestDatabaseAutoConfiguration.class); .withConfiguration(
AutoConfigurations.of(TestDatabaseAutoConfiguration.class));
@Test @Test
public void applyAnyReplace() { public void applyAnyReplace() {
this.contextLoader.loadAndFail(BeanCreationException.class, ex -> { this.context.run((loaded) -> {
String message = ex.getMessage(); assertThat(loaded).getFailure().isInstanceOf(BeanCreationException.class)
assertThat(message).contains( .hasMessageContaining(
"Failed to replace DataSource with an embedded database for tests."); "Failed to replace DataSource with an embedded database for tests.")
assertThat(message).contains( .hasMessageContaining(
"If you want an embedded database please put a supported one on the " "If you want an embedded database please put a supported one on the classpath")
+ "classpath"); .hasMessageContaining(
assertThat(message).contains( "or tune the replace attribute of @AutoconfigureTestDatabase.");
"or tune the replace attribute of @AutoconfigureTestDatabase.");
}); });
} }
@Test @Test
public void applyNoReplace() { public void applyNoReplace() {
this.contextLoader.env("spring.test.database.replace=NONE").load(context -> { this.context.withPropertyValues("spring.test.database.replace=NONE")
assertThat(context.getBeansOfType(DataSource.class)).hasSize(1); .run((loaded) -> {
assertThat(context.getBean(DataSource.class)) assertThat(loaded).hasSingleBean(DataSource.class);
.isSameAs(context.getBean("myCustomDataSource")); assertThat(loaded).getBean(DataSource.class)
}); .isSameAs(loaded.getBean("myCustomDataSource"));
});
} }
@Configuration @Configuration