diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java index 16f6729da692..0e2a0e76d9bb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +21,11 @@ import java.util.Set; import java.util.stream.Collectors; -import org.junit.After; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Test; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisNode; @@ -52,138 +52,169 @@ */ public class RedisAutoConfigurationTests { - private AnnotationConfigApplicationContext context; - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test public void testDefaultRedisConfiguration() { - load(); - assertThat(this.context.getBean("redisTemplate", RedisOperations.class)) - .isNotNull(); - assertThat(this.context.getBean(StringRedisTemplate.class)).isNotNull(); + this.contextRunner.run((context) -> { + assertThat(context.getBean("redisTemplate", RedisOperations.class)) + .isNotNull(); + assertThat(context.getBean(StringRedisTemplate.class)).isNotNull(); + }); } @Test public void testOverrideRedisConfiguration() { - load("spring.redis.host:foo", "spring.redis.database:1", - "spring.redis.lettuce.shutdown-timeout:500"); - LettuceConnectionFactory cf = this.context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getDatabase()).isEqualTo(1); - assertThat(cf.getPassword()).isNull(); - assertThat(cf.isUseSsl()).isFalse(); - assertThat(cf.getShutdownTimeout()).isEqualTo(500); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", + "spring.redis.database:1", + "spring.redis.lettuce.shutdown-timeout:500") + .run((context) -> { + LettuceConnectionFactory cf = context + .getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getDatabase()).isEqualTo(1); + assertThat(cf.getPassword()).isNull(); + assertThat(cf.isUseSsl()).isFalse(); + assertThat(cf.getShutdownTimeout()).isEqualTo(500); + }); } @Test public void testCustomizeRedisConfiguration() { - load(CustomConfiguration.class); - LettuceConnectionFactory cf = this.context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.isUseSsl()).isTrue(); + this.contextRunner + .withUserConfiguration(CustomConfiguration.class) + .run((context) -> { + LettuceConnectionFactory cf = context + .getBean(LettuceConnectionFactory.class); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test public void testRedisUrlConfiguration() { - load("spring.redis.host:foo", - "spring.redis.url:redis://user:password@example:33"); - LettuceConnectionFactory cf = this.context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isFalse(); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", + "spring.redis.url:redis://user:password@example:33") + .run((context) -> { + LettuceConnectionFactory cf = context + .getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isFalse(); + }); } @Test public void testOverrideUrlRedisConfiguration() { - load("spring.redis.host:foo", "spring.redis.password:xyz", - "spring.redis.port:1000", "spring.redis.ssl:false", - "spring.redis.url:rediss://user:password@example:33"); - LettuceConnectionFactory cf = this.context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isTrue(); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", "spring.redis.password:xyz", + "spring.redis.port:1000", "spring.redis.ssl:false", + "spring.redis.url:rediss://user:password@example:33") + .run((context) -> { + LettuceConnectionFactory cf = context + .getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test public void testRedisConfigurationWithPool() { - load("spring.redis.host:foo", "spring.redis.lettuce.pool.min-idle:1", - "spring.redis.lettuce.pool.max-idle:4", - "spring.redis.lettuce.pool.max-active:16", - "spring.redis.lettuce.pool.max-wait:2000", - "spring.redis.lettuce.shutdown-timeout:1000"); - LettuceConnectionFactory cf = this.context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(getPoolingClientConfiguration(cf).getPoolConfig().getMinIdle()) - .isEqualTo(1); - assertThat(getPoolingClientConfiguration(cf).getPoolConfig().getMaxIdle()) - .isEqualTo(4); - assertThat(getPoolingClientConfiguration(cf).getPoolConfig().getMaxTotal()) - .isEqualTo(16); - assertThat(getPoolingClientConfiguration(cf).getPoolConfig().getMaxWaitMillis()) - .isEqualTo(2000); - assertThat(cf.getShutdownTimeout()).isEqualTo(1000); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", + "spring.redis.lettuce.pool.min-idle:1", + "spring.redis.lettuce.pool.max-idle:4", + "spring.redis.lettuce.pool.max-active:16", + "spring.redis.lettuce.pool.max-wait:2000", + "spring.redis.lettuce.shutdown-timeout:1000") + .run((context) -> { + LettuceConnectionFactory cf = context + .getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + GenericObjectPoolConfig poolConfig = + getPoolingClientConfiguration(cf).getPoolConfig(); + assertThat(poolConfig.getMinIdle()).isEqualTo(1); + assertThat(poolConfig.getMaxIdle()).isEqualTo(4); + assertThat(poolConfig.getMaxTotal()).isEqualTo(16); + assertThat(poolConfig.getMaxWaitMillis()).isEqualTo(2000); + assertThat(cf.getShutdownTimeout()).isEqualTo(1000); + }); } @Test public void testRedisConfigurationWithTimeout() { - load("spring.redis.host:foo", "spring.redis.timeout:100"); - LettuceConnectionFactory cf = this.context - .getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getTimeout()).isEqualTo(100); + this.contextRunner + .withPropertyValues("spring.redis.host:foo", + "spring.redis.timeout:100") + .run((context) -> { + LettuceConnectionFactory cf = context + .getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getTimeout()).isEqualTo(100); + }); } @Test public void testRedisConfigurationWithSentinel() { List sentinels = Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380"); - load("spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:" - + StringUtils.collectionToCommaDelimitedString(sentinels)); - assertThat(this.context.getBean(LettuceConnectionFactory.class) - .isRedisSentinelAware()).isTrue(); + this.contextRunner + .withPropertyValues("spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:" + + StringUtils.collectionToCommaDelimitedString(sentinels)) + .run((context) -> { + assertThat(context.getBean(LettuceConnectionFactory.class) + .isRedisSentinelAware()).isTrue(); + + }); } @Test public void testRedisConfigurationWithSentinelAndPassword() { - load("spring.redis.password=password", "spring.redis.sentinel.master:mymaster", - "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380"); - LettuceConnectionFactory connectionFactory = this.context - .getBean(LettuceConnectionFactory.class); - assertThat(connectionFactory.getPassword()).isEqualTo("password"); - Set sentinels = connectionFactory.getSentinelConfiguration() - .getSentinels(); - assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) - .contains("127.0.0.1:26379", "127.0.0.1:26380"); + this.contextRunner + .withPropertyValues("spring.redis.password=password", + "spring.redis.sentinel.master:mymaster", + "spring.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run((context) -> { + LettuceConnectionFactory connectionFactory = context + .getBean(LettuceConnectionFactory.class); + assertThat(connectionFactory.getPassword()).isEqualTo("password"); + Set sentinels = connectionFactory.getSentinelConfiguration() + .getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); + }); } @Test public void testRedisConfigurationWithCluster() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); - load("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), - "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)); - assertThat(this.context.getBean(LettuceConnectionFactory.class) - .getClusterConnection()).isNotNull(); + this.contextRunner + .withPropertyValues("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), + "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)) + .run((context) -> { + assertThat(context.getBean(LettuceConnectionFactory.class) + .getClusterConnection()).isNotNull(); + + }); } @Test public void testRedisConfigurationWithClusterAndPassword() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); - load("spring.redis.password=password", - "spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), - "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)); - assertThat(this.context.getBean(LettuceConnectionFactory.class).getPassword()) - .isEqualTo("password"); + this.contextRunner + .withPropertyValues("spring.redis.password=password", + "spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), + "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)) + .run((context) -> { + assertThat(context.getBean(LettuceConnectionFactory.class).getPassword()) + .isEqualTo("password"); + + }); } private LettucePoolingClientConfiguration getPoolingClientConfiguration( @@ -192,21 +223,6 @@ private LettucePoolingClientConfiguration getPoolingClientConfiguration( "clientConfiguration"); } - private void load(String... environment) { - load(null, environment); - } - - private void load(Class config, String... environment) { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - TestPropertyValues.of(environment).applyTo(ctx); - if (config != null) { - ctx.register(config); - } - ctx.register(RedisAutoConfiguration.class); - ctx.refresh(); - this.context = ctx; - } - @Configuration static class CustomConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java index 5991f5a841bd..33f2a415ac8b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,10 @@ import java.util.Map; -import org.junit.After; import org.junit.Test; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.data.redis.core.ReactiveRedisTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -34,28 +33,16 @@ */ public class RedisReactiveAutoConfigurationTests { - private AnnotationConfigApplicationContext context; - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations + .of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); @Test public void testDefaultRedisConfiguration() { - load(); - Map beans = this.context.getBeansOfType(ReactiveRedisTemplate.class); - assertThat(beans).containsOnlyKeys("reactiveRedisTemplate"); - } - - private void load(String... environment) { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - TestPropertyValues.of(environment).applyTo(ctx); - ctx.register(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class); - ctx.refresh(); - this.context = ctx; + this.contextRunner.run((context) -> { + Map beans = context.getBeansOfType(ReactiveRedisTemplate.class); + assertThat(beans).containsOnlyKeys("reactiveRedisTemplate"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java index 01273d805301..b6ca56061926 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,18 +31,16 @@ import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.BeanCreationException; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchNodeTemplate; import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration; -import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testsupport.runner.classpath.ClassPathOverrides; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -60,79 +58,94 @@ @ClassPathOverrides("org.apache.logging.log4j:log4j-core:2.10.0") public class JestAutoConfigurationTests { + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations + .of(GsonAutoConfiguration.class, JestAutoConfiguration.class)); + @Before public void preventElasticsearchFromConfiguringNetty() { System.setProperty("es.set.netty.runtime.available.processors", "false"); } - @Rule - public ExpectedException thrown = ExpectedException.none(); - - protected AnnotationConfigApplicationContext context; - @After public void close() { - if (this.context != null) { - this.context.close(); - } System.clearProperty("es.set.netty.runtime.available.processors"); } @Test public void jestClientOnLocalhostByDefault() { - load(); - assertThat(this.context.getBeansOfType(JestClient.class)).hasSize(1); + this.contextRunner.run((context) -> { + assertThat(context.getBeansOfType(JestClient.class)).hasSize(1); + }); } @Test public void customJestClient() { - load(CustomJestClient.class, - "spring.elasticsearch.jest.uris[0]=http://localhost:9200"); - assertThat(this.context.getBeansOfType(JestClient.class)).hasSize(1); + this.contextRunner + .withUserConfiguration(CustomJestClient.class) + .withPropertyValues("spring.elasticsearch.jest.uris[0]=http://localhost:9200") + .run((context) -> { + assertThat(context.getBeansOfType(JestClient.class)).hasSize(1); + }); } @Test public void customGson() { - load(CustomGson.class, "spring.elasticsearch.jest.uris=http://localhost:9200"); - JestHttpClient client = (JestHttpClient) this.context.getBean(JestClient.class); - assertThat(client.getGson()).isSameAs(this.context.getBean("customGson")); + this.contextRunner + .withUserConfiguration(CustomGson.class) + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200") + .run((context) -> { + JestHttpClient client = (JestHttpClient) context.getBean(JestClient.class); + assertThat(client.getGson()).isSameAs(context.getBean("customGson")); + }); } @Test public void customizerOverridesAutoConfig() { - load(BuilderCustomizer.class, - "spring.elasticsearch.jest.uris=http://localhost:9200"); - JestHttpClient client = (JestHttpClient) this.context.getBean(JestClient.class); - assertThat(client.getGson()) - .isSameAs(this.context.getBean(BuilderCustomizer.class).getGson()); + this.contextRunner + .withUserConfiguration(BuilderCustomizer.class) + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200") + .run((context) -> { + JestHttpClient client = (JestHttpClient) context.getBean(JestClient.class); + assertThat(client.getGson()) + .isSameAs(context.getBean(BuilderCustomizer.class).getGson()); + }); } @Test public void proxyHostWithoutPort() { - this.thrown.expect(BeanCreationException.class); - this.thrown.expectMessage("Proxy port must not be null"); - load("spring.elasticsearch.jest.uris=http://localhost:9200", - "spring.elasticsearch.jest.proxy.host=proxy.example.com"); + this.contextRunner + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:9200", + "spring.elasticsearch.jest.proxy.host=proxy.example.com") + .run((context) -> { + assertThat(context.getStartupFailure()) + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Proxy port must not be null"); + }); } @Test public void jestCanCommunicateWithElasticsearchInstance() { - new ElasticsearchNodeTemplate().doWithNode((node) -> { - load("spring.elasticsearch.jest.uris=http://localhost:" + node.getHttpPort()); - JestClient client = this.context.getBean(JestClient.class); - Map source = new HashMap<>(); - source.put("a", "alpha"); - source.put("b", "bravo"); - Index index = new Index.Builder(source).index("foo").type("bar").build(); - execute(client, index); - SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.query(QueryBuilders.matchQuery("a", "alpha")); - assertThat( - execute(client, - new Search.Builder(searchSourceBuilder.toString()) - .addIndex("foo").build()).getResponseCode()) - .isEqualTo(200); - }); + new ElasticsearchNodeTemplate().doWithNode((node) -> + this.contextRunner + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:" + + node.getHttpPort()) + .run((context) -> { + JestClient client = context.getBean(JestClient.class); + Map source = new HashMap<>(); + source.put("a", "alpha"); + source.put("b", "bravo"); + Index index = new Index.Builder(source).index("foo").type("bar").build(); + execute(client, index); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + searchSourceBuilder.query(QueryBuilders.matchQuery("a", "alpha")); + assertThat( + execute(client, + new Search.Builder(searchSourceBuilder.toString()) + .addIndex("foo").build()).getResponseCode()) + .isEqualTo(200); + }) + ); } private JestResult execute(JestClient client, Action action) { @@ -144,21 +157,6 @@ private JestResult execute(JestClient client, Action actio } } - private void load(String... environment) { - load(null, environment); - } - - private void load(Class config, String... environment) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of(environment).applyTo(context); - if (config != null) { - context.register(config); - } - context.register(GsonAutoConfiguration.class, JestAutoConfiguration.class); - context.refresh(); - this.context = context; - } - @Configuration static class CustomJestClient { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java index 5fd0c3f543a2..b564430137b1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java @@ -16,17 +16,15 @@ package org.springframework.boot.autoconfigure.info; -import java.util.Map; import java.util.Properties; -import org.junit.After; import org.junit.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.info.BuildProperties; import org.springframework.boot.info.GitProperties; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -39,90 +37,86 @@ */ public class ProjectInfoAutoConfigurationTests { - private AnnotationConfigApplicationContext context; + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + ProjectInfoAutoConfiguration.class)); - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } @Test public void gitPropertiesUnavailableIfResourceNotAvailable() { - load(); - Map beans = this.context - .getBeansOfType(GitProperties.class); - assertThat(beans).hasSize(0); + this.contextRunner.run((context) -> { + assertThat(context.getBeansOfType(GitProperties.class)).isEmpty(); + }); } @Test public void gitPropertiesWithNoData() { - load("spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties"); - GitProperties gitProperties = this.context.getBean(GitProperties.class); - assertThat(gitProperties.getBranch()).isNull(); + this.contextRunner.withPropertyValues( + "spring.info.git.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties.getBranch()).isNull(); + }); } @Test public void gitPropertiesFallbackWithGitPropertiesBean() { - load(CustomInfoPropertiesConfiguration.class, - "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties"); - GitProperties gitProperties = this.context.getBean(GitProperties.class); - assertThat(gitProperties).isSameAs(this.context.getBean("customGitProperties")); + this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class) + .withPropertyValues("spring.info.git.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/git.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties).isSameAs(context.getBean("customGitProperties")); + }); } @Test public void buildPropertiesDefaultLocation() { - load(); - BuildProperties buildProperties = this.context.getBean(BuildProperties.class); - assertThat(buildProperties.getGroup()).isEqualTo("com.example"); - assertThat(buildProperties.getArtifact()).isEqualTo("demo"); - assertThat(buildProperties.getName()).isEqualTo("Demo Project"); - assertThat(buildProperties.getVersion()).isEqualTo("0.0.1-SNAPSHOT"); - assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457100965000L); + this.contextRunner.run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.getGroup()).isEqualTo("com.example"); + assertThat(buildProperties.getArtifact()).isEqualTo("demo"); + assertThat(buildProperties.getName()).isEqualTo("Demo Project"); + assertThat(buildProperties.getVersion()).isEqualTo("0.0.1-SNAPSHOT"); + assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457100965000L); + }); } @Test public void buildPropertiesCustomLocation() { - load("spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties"); - BuildProperties buildProperties = this.context.getBean(BuildProperties.class); - assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme"); - assertThat(buildProperties.getArtifact()).isEqualTo("acme"); - assertThat(buildProperties.getName()).isEqualTo("acme"); - assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT"); - assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457088120000L); + this.contextRunner + .withPropertyValues("spring.info.build.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme"); + assertThat(buildProperties.getArtifact()).isEqualTo("acme"); + assertThat(buildProperties.getName()).isEqualTo("acme"); + assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT"); + assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457088120000L); + }); } @Test public void buildPropertiesCustomInvalidLocation() { - load("spring.info.build.location=classpath:/org/acme/no-build-info.properties"); - Map beans = this.context - .getBeansOfType(BuildProperties.class); - assertThat(beans).hasSize(0); + this.contextRunner + .withPropertyValues("spring.info.build.location=" + + "classpath:/org/acme/no-build-info.properties") + .run((context) -> { + assertThat(context.getBeansOfType(BuildProperties.class)).hasSize(0); + }); } @Test public void buildPropertiesFallbackWithBuildInfoBean() { - load(CustomInfoPropertiesConfiguration.class); - BuildProperties buildProperties = this.context.getBean(BuildProperties.class); - assertThat(buildProperties) - .isSameAs(this.context.getBean("customBuildProperties")); - } - - private void load(String... environment) { - load(null, environment); - } - - private void load(Class config, String... environment) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - if (config != null) { - context.register(config); - } - context.register(PropertyPlaceholderAutoConfiguration.class, - ProjectInfoAutoConfiguration.class); - TestPropertyValues.of(environment).applyTo(context); - context.refresh(); - this.context = context; + this.contextRunner + .withUserConfiguration(CustomInfoPropertiesConfiguration.class) + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties) + .isSameAs(context.getBean("customBuildProperties")); + }); } @Configuration diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java index 2bafd7464abc..05a769415db4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +21,10 @@ import javax.sql.DataSource; import com.zaxxer.hikari.HikariDataSource; -import org.junit.After; import org.junit.Test; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -38,60 +37,72 @@ */ public class HikariDataSourceConfigurationTests { - private AnnotationConfigApplicationContext context; - - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.initialization-mode=never", + "spring.datasource.type=" + HikariDataSource.class.getName()); @Test public void testDataSourceExists() { - load(); - assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); - assertThat(this.context.getBeansOfType(HikariDataSource.class)).hasSize(1); + this.contextRunner.run((context) -> { + assertThat(context.getBeansOfType(DataSource.class)).hasSize(1); + assertThat(context.getBeansOfType(HikariDataSource.class)).hasSize(1); + }); } @Test public void testDataSourcePropertiesOverridden() { - load("spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", - "spring.datasource.hikari.max-lifetime=1234"); - HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); - assertThat(ds.getMaxLifetime()).isEqualTo(1234); + this.contextRunner.withPropertyValues( + "spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", + "spring.datasource.hikari.max-lifetime=1234") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); + assertThat(ds.getMaxLifetime()).isEqualTo(1234); + }); // TODO: test JDBC4 isValid() } @Test public void testDataSourceGenericPropertiesOverridden() { - load("spring.datasource.hikari.data-source-properties.dataSourceClassName=org.h2.JDBCDataSource"); - HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) - .isEqualTo("org.h2.JDBCDataSource"); + this.contextRunner.withPropertyValues( + "spring.datasource.hikari.data-source-properties" + + ".dataSourceClassName=org.h2.JDBCDataSource") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) + .isEqualTo("org.h2.JDBCDataSource"); + + }); } @Test public void testDataSourceDefaultsPreserved() { - load(); - HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertThat(ds.getMaxLifetime()).isEqualTo(1800000); + this.contextRunner.run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getMaxLifetime()).isEqualTo(1800000); + }); } @Test public void nameIsAliasedToPoolName() { - load("spring.datasource.name=myDS"); - HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertThat(ds.getPoolName()).isEqualTo("myDS"); + this.contextRunner.withPropertyValues("spring.datasource.name=myDS") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getPoolName()).isEqualTo("myDS"); + + }); } @Test public void poolNameTakesPrecedenceOverName() { - load("spring.datasource.name=myDS", - "spring.datasource.hikari.pool-name=myHikariDS"); - HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertThat(ds.getPoolName()).isEqualTo("myHikariDS"); + this.contextRunner.withPropertyValues( + "spring.datasource.name=myDS", + "spring.datasource.hikari.pool-name=myHikariDS") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getPoolName()).isEqualTo("myHikariDS"); + }); } @SuppressWarnings("unchecked") @@ -101,15 +112,4 @@ public static T getField(Class target, String name) { return (T) ReflectionUtils.getField(field, target); } - private void load(String... environment) { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - TestPropertyValues.of(environment) - .and("spring.datasource.initialization-mode=never") - .and("spring.datasource.type=" + HikariDataSource.class.getName()) - .applyTo(ctx); - ctx.register(DataSourceAutoConfiguration.class); - ctx.refresh(); - this.context = ctx; - } - } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index 2855a064bd2e..7b866991d38d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,20 +31,18 @@ import org.jooq.TransactionalRunnable; import org.jooq.VisitListener; import org.jooq.VisitListenerProvider; -import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.jdbc.DataSourceBuilder; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.util.ObjectUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -61,116 +59,111 @@ public class JooqAutoConfigurationTests { private static final String[] NO_BEANS = {}; - @Rule - public ExpectedException thrown = ExpectedException.none(); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) + .withPropertyValues("spring.datasource.name:jooqtest"); - private AnnotationConfigApplicationContext context; - @After - public void close() { - if (this.context != null) { - this.context.close(); - } - } + @Rule + public ExpectedException thrown = ExpectedException.none(); @Test public void noDataSource() { - load(); - assertThat(this.context.getBeanNamesForType(DSLContext.class).length) - .isEqualTo(0); + this.contextRunner.run((context) -> { + assertThat(context.getBeansOfType(DSLContext.class)).isEmpty(); + }); } @Test public void jooqWithoutTx() { - load(JooqDataSourceConfiguration.class); - assertThat(getBeanNames(PlatformTransactionManager.class)).isEqualTo(NO_BEANS); - assertThat(getBeanNames(SpringTransactionProvider.class)).isEqualTo(NO_BEANS); - DSLContext dsl = this.context.getBean(DSLContext.class); - dsl.execute("create table jooqtest (name varchar(255) primary key);"); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest;", "0")); - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); - try { - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + this.contextRunner + .withUserConfiguration(JooqDataSourceConfiguration.class) + .run((context) -> { + assertThat(context.getBeanNamesForType( + PlatformTransactionManager.class)).isEqualTo(NO_BEANS); + assertThat(context.getBeanNamesForType( + SpringTransactionProvider.class)).isEqualTo(NO_BEANS); + DSLContext dsl = context.getBean(DSLContext.class); + dsl.execute("create table jooqtest (name varchar(255) primary key);"); + dsl.transaction(new AssertFetch(dsl, + "select count(*) as total from jooqtest;", "0")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); - fail("An DataIntegrityViolationException should have been thrown."); - } - catch (DataIntegrityViolationException ex) { - // Ignore - } - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); + dsl.transaction(new AssertFetch(dsl, + "select count(*) as total from jooqtest;", "1")); + try { + dsl.transaction( + new ExecuteSql(dsl, + "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');")); + fail("An DataIntegrityViolationException should have been thrown."); + } + catch (DataIntegrityViolationException ex) { + // Ignore + } + dsl.transaction( + new AssertFetch(dsl, + "select count(*) as total from jooqtest;", "2")); + + }); } @Test public void jooqWithTx() { - load(JooqDataSourceConfiguration.class, TxManagerConfiguration.class); - this.context.getBean(PlatformTransactionManager.class); - DSLContext dsl = this.context.getBean(DSLContext.class); - assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); - dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); - try { - dsl.transaction( - new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');")); - fail("A DataIntegrityViolationException should have been thrown."); - } - catch (DataIntegrityViolationException ex) { - // Ignore - } - dsl.transaction( - new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + this.contextRunner + .withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class) + .run((context) -> { + context.getBean(PlatformTransactionManager.class); + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); + dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); + dsl.transaction(new AssertFetch(dsl, + "select count(*) as total from jooqtest_tx;", "0")); + dsl.transaction(new ExecuteSql(dsl, + "insert into jooqtest_tx (name) values ('foo');")); + dsl.transaction(new AssertFetch(dsl, + "select count(*) as total from jooqtest_tx;", "1")); + try { + dsl.transaction( + new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');")); + fail("A DataIntegrityViolationException should have been thrown."); + } + catch (DataIntegrityViolationException ex) { + // Ignore + } + dsl.transaction( + new AssertFetch(dsl, + "select count(*) as total from jooqtest_tx;", "1")); + + }); } @Test public void customProvidersArePickedUp() { - load(JooqDataSourceConfiguration.class, TxManagerConfiguration.class, - TestRecordMapperProvider.class, TestRecordListenerProvider.class, - TestExecuteListenerProvider.class, TestVisitListenerProvider.class); - DSLContext dsl = this.context.getBean(DSLContext.class); - assertThat(dsl.configuration().recordMapperProvider().getClass()) - .isEqualTo(TestRecordMapperProvider.class); - assertThat(dsl.configuration().recordListenerProviders().length).isEqualTo(1); - assertThat(dsl.configuration().executeListenerProviders().length).isEqualTo(2); - assertThat(dsl.configuration().visitListenerProviders().length).isEqualTo(1); + this.contextRunner + .withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class, + TestRecordMapperProvider.class, TestRecordListenerProvider.class, + TestExecuteListenerProvider.class, TestVisitListenerProvider.class) + .run((context) -> { + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().recordMapperProvider().getClass()) + .isEqualTo(TestRecordMapperProvider.class); + assertThat(dsl.configuration().recordListenerProviders().length).isEqualTo(1); + assertThat(dsl.configuration().executeListenerProviders().length).isEqualTo(2); + assertThat(dsl.configuration().visitListenerProviders().length).isEqualTo(1); + }); } @Test public void relaxedBindingOfSqlDialect() { - load(new Class[] { JooqDataSourceConfiguration.class }, - "spring.jooq.sql-dialect:PoSTGrES"); - assertThat(this.context.getBean(org.jooq.Configuration.class).dialect()) - .isEqualTo(SQLDialect.POSTGRES); - } - - private void load(Class... configs) { - load(configs, new String[0]); - } - - private void load(Class[] configs, String... environment) { - AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.name:jooqtest").applyTo(ctx); - TestPropertyValues.of(environment).applyTo(ctx); - if (!ObjectUtils.isEmpty(configs)) { - ctx.register(configs); - } - ctx.register(JooqAutoConfiguration.class); - ctx.refresh(); - this.context = ctx; - } - - private String[] getBeanNames(Class type) { - return this.context.getBeanNamesForType(type); + this.contextRunner + .withUserConfiguration(JooqDataSourceConfiguration.class) + .withPropertyValues("spring.jooq.sql-dialect:PoSTGrES") + .run((context) -> { + assertThat(context.getBean(org.jooq.Configuration.class) + .dialect()).isEqualTo(SQLDialect.POSTGRES); + }); } private static class AssertFetch implements TransactionalRunnable {