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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,14 +16,17 @@
package org.springframework.boot.autoconfigure.webservices;
import java.util.Collection;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.test.context.ContextLoader;
import org.springframework.boot.test.context.ServletWebContextLoader;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.WebApplicationContextTester;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
@ -37,52 +40,46 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class WebServicesAutoConfigurationTests {
private final ServletWebContextLoader contextLoader = ContextLoader.servletWeb()
.autoConfig(WebServicesAutoConfiguration.class);
private final WebApplicationContextTester context = new WebApplicationContextTester()
.withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class));
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void defaultConfiguration() {
this.contextLoader.load(context -> {
assertThat(context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1);
});
this.context.run((loaded) -> assertThat(loaded)
.hasSingleBean(ServletRegistrationBean.class));
}
@Test
public void customPathMustBeginWithASlash() {
this.contextLoader.env("spring.webservices.path=invalid")
.loadAndFail(BeanCreationException.class, (ex) -> {
System.out.println(ex.getMessage());
assertThat(ex.getMessage()).contains(
"Failed to bind properties under 'spring.webservices'");
this.context.withPropertyValues("spring.webservices.path=invalid")
.run((loaded) -> {
assertThat(loaded).getFailure()
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining(
"Failed to bind properties under 'spring.webservices'");
});
}
@Test
public void customPath() {
this.contextLoader.env("spring.webservices.path=/valid").load(context -> {
ServletRegistrationBean<?> servletRegistrationBean = context
.getBean(ServletRegistrationBean.class);
assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*");
});
this.context.withPropertyValues("spring.webservices.path=/valid")
.run((loaded) -> assertThat(getUrlMappings(loaded)).contains("/valid/*"));
}
@Test
public void customPathWithTrailingSlash() {
this.contextLoader.env("spring.webservices.path=/valid/").load(context -> {
ServletRegistrationBean<?> servletRegistrationBean = context
.getBean(ServletRegistrationBean.class);
assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*");
});
this.context.withPropertyValues("spring.webservices.path=/valid/")
.run((loaded) -> assertThat(getUrlMappings(loaded)).contains("/valid/*"));
}
@Test
public void customLoadOnStartup() {
this.contextLoader.env("spring.webservices.servlet.load-on-startup=1")
.load(context -> {
ServletRegistrationBean<?> registrationBean = context
this.context.withPropertyValues("spring.webservices.servlet.load-on-startup=1")
.run((loaded) -> {
ServletRegistrationBean<?> registrationBean = loaded
.getBean(ServletRegistrationBean.class);
assertThat(ReflectionTestUtils.getField(registrationBean,
"loadOnStartup")).isEqualTo(1);
@ -91,15 +88,22 @@ public class WebServicesAutoConfigurationTests {
@Test
public void customInitParameters() {
this.contextLoader.env("spring.webservices.servlet.init.key1=value1",
"spring.webservices.servlet.init.key2=value2").load(context -> {
ServletRegistrationBean<?> registrationBean = context
.getBean(ServletRegistrationBean.class);
assertThat(registrationBean.getInitParameters()).containsEntry("key1",
"value1");
assertThat(registrationBean.getInitParameters()).containsEntry("key2",
"value2");
});
this.context
.withPropertyValues("spring.webservices.servlet.init.key1=value1",
"spring.webservices.servlet.init.key2=value2")
.run(loaded -> assertThat(
getServletRegistrationBean(loaded).getInitParameters())
.containsEntry("key1", "value1")
.containsEntry("key2", "value2"));
}
private Collection<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.springframework.boot.test.context.ContextLoader;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.ApplicationContextTester;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
@ -37,29 +38,32 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class TestDatabaseAutoConfigurationTests {
private final ContextLoader contextLoader = ContextLoader.standard()
.autoConfig(TestDatabaseAutoConfiguration.class);
private final ApplicationContextTester context = new ApplicationContextTester()
.withConfiguration(
AutoConfigurations.of(TestDatabaseAutoConfiguration.class));
@Test
public void replaceWithNoDataSourceAvailable() {
this.contextLoader.load(context -> {
assertThat(context.getBeansOfType(DataSource.class)).isEmpty();
});
this.context
.run((loaded) -> assertThat(loaded).doesNotHaveBean(DataSource.class));
}
@Test
public void replaceWithUniqueDatabase() {
this.contextLoader.config(ExistingDataSourceConfiguration.class).load(context -> {
DataSource datasource = context.getBean(DataSource.class);
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
jdbcTemplate.execute("create table example (id int, name varchar);");
this.contextLoader.load(anotherContext -> {
DataSource anotherDatasource = anotherContext.getBean(DataSource.class);
JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource);
anotherJdbcTemplate
.execute("create table example (id int, name varchar);");
});
});
this.context.withUserConfiguration(ExistingDataSourceConfiguration.class)
.run((loaded) -> {
DataSource datasource = loaded.getBean(DataSource.class);
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
jdbcTemplate.execute("create table example (id int, name varchar);");
this.context.run((secondContext) -> {
DataSource anotherDatasource = secondContext
.getBean(DataSource.class);
JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(
anotherDatasource);
anotherJdbcTemplate
.execute("create table example (id int, name varchar);");
});
});
}
@Configuration

View File

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