Migrate some more tests to the new ContextLoader

pull/9688/merge
Andy Wilkinson 7 years ago committed by Stephane Nicoll
parent e91b4d0bb3
commit 19ddfad63e

@ -16,12 +16,9 @@
package org.springframework.boot.autoconfigure.web.reactive; package org.springframework.boot.autoconfigure.web.reactive;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.context.ContextLoader;
import org.springframework.boot.web.reactive.context.GenericReactiveWebApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.HttpHandler;
@ -37,36 +34,27 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Brian Clozel * @author Brian Clozel
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Andy Wilkinson
*/ */
public class HttpHandlerAutoConfigurationTests { public class HttpHandlerAutoConfigurationTests {
@Rule private final ContextLoader contextLoader = new ContextLoader().webReactive()
public ExpectedException thrown = ExpectedException.none(); .autoConfig(HttpHandlerAutoConfiguration.class);
private GenericReactiveWebApplicationContext context;
@Test @Test
public void shouldNotProcessIfExistingHttpHandler() { public void shouldNotProcessIfExistingHttpHandler() {
load(CustomHttpHandler.class); this.contextLoader.config(CustomHttpHandler.class).load(context -> {
assertThat(this.context.getBeansOfType(HttpHandler.class)).hasSize(1); assertThat(context.getBeansOfType(HttpHandler.class)).hasSize(1);
assertThat(this.context.getBean(HttpHandler.class)) assertThat(context.getBean(HttpHandler.class))
.isSameAs(this.context.getBean("customHttpHandler")); .isSameAs(context.getBean("customHttpHandler"));
});
} }
@Test @Test
public void shouldConfigureHttpHandlerAnnotation() { public void shouldConfigureHttpHandlerAnnotation() {
load(WebFluxAutoConfiguration.class); this.contextLoader.autoConfig(WebFluxAutoConfiguration.class).load(context -> {
assertThat(this.context.getBeansOfType(HttpHandler.class).size()).isEqualTo(1); assertThat(context.getBeansOfType(HttpHandler.class).size()).isEqualTo(1);
} });
private void load(Class<?> config, String... environment) {
this.context = new GenericReactiveWebApplicationContext();
TestPropertyValues.of(environment).applyTo(this.context);
if (this.context != null) {
this.context.register(config);
}
this.context.register(HttpHandlerAutoConfiguration.class);
this.context.refresh();
} }
@Configuration @Configuration

@ -16,17 +16,14 @@
package org.springframework.boot.autoconfigure.webservices; package org.springframework.boot.autoconfigure.webservices;
import org.junit.After;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.context.ContextLoader;
import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -35,79 +32,73 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Vedran Pavic * @author Vedran Pavic
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Andy Wilkinson
*/ */
public class WebServicesAutoConfigurationTests { public class WebServicesAutoConfigurationTests {
private final ContextLoader contextLoader = new ContextLoader().webServlet()
.autoConfig(WebServicesAutoConfiguration.class);
@Rule @Rule
public ExpectedException thrown = ExpectedException.none(); public ExpectedException thrown = ExpectedException.none();
private AnnotationConfigWebApplicationContext context;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test @Test
public void defaultConfiguration() { public void defaultConfiguration() {
load(WebServicesAutoConfiguration.class); this.contextLoader.load(context -> {
assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); assertThat(context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1);
});
} }
@Test @Test
public void customPathMustBeginWithASlash() { public void customPathMustBeginWithASlash() {
this.thrown.expect(BeanCreationException.class); this.contextLoader.env("spring.webservices.path=invalid")
this.thrown.expectMessage("Failed to bind properties under 'spring.webservices'"); .loadAndFail(BeanCreationException.class, (ex) -> {
load(WebServicesAutoConfiguration.class, "spring.webservices.path=invalid"); System.out.println(ex.getMessage());
assertThat(ex.getMessage()).contains(
"Failed to bind properties under 'spring.webservices'");
});
} }
@Test @Test
public void customPathWithTrailingSlash() { public void customPath() {
load(WebServicesAutoConfiguration.class, "spring.webservices.path=/valid/"); this.contextLoader.env("spring.webservices.path=/valid").load(context -> {
ServletRegistrationBean<?> servletRegistrationBean = this.context ServletRegistrationBean<?> servletRegistrationBean = context
.getBean(ServletRegistrationBean.class); .getBean(ServletRegistrationBean.class);
assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*"); assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*");
});
} }
@Test @Test
public void customPath() { public void customPathWithTrailingSlash() {
load(WebServicesAutoConfiguration.class, "spring.webservices.path=/valid"); this.contextLoader.env("spring.webservices.path=/valid/").load(context -> {
assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); ServletRegistrationBean<?> servletRegistrationBean = context
ServletRegistrationBean<?> servletRegistrationBean = this.context .getBean(ServletRegistrationBean.class);
.getBean(ServletRegistrationBean.class); assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*");
assertThat(servletRegistrationBean.getUrlMappings()).contains("/valid/*"); });
} }
@Test @Test
public void customLoadOnStartup() { public void customLoadOnStartup() {
load(WebServicesAutoConfiguration.class, this.contextLoader.env("spring.webservices.servlet.load-on-startup=1")
"spring.webservices.servlet.load-on-startup=1"); .load(context -> {
ServletRegistrationBean<?> registrationBean = this.context ServletRegistrationBean<?> registrationBean = context
.getBean(ServletRegistrationBean.class); .getBean(ServletRegistrationBean.class);
assertThat(ReflectionTestUtils.getField(registrationBean, "loadOnStartup")) assertThat(ReflectionTestUtils.getField(registrationBean,
.isEqualTo(1); "loadOnStartup")).isEqualTo(1);
});
} }
@Test @Test
public void customInitParameters() { public void customInitParameters() {
load(WebServicesAutoConfiguration.class, this.contextLoader.env("spring.webservices.servlet.init.key1=value1",
"spring.webservices.servlet.init.key1=value1", "spring.webservices.servlet.init.key2=value2").load(context -> {
"spring.webservices.servlet.init.key2=value2"); ServletRegistrationBean<?> registrationBean = context
ServletRegistrationBean<?> registrationBean = this.context .getBean(ServletRegistrationBean.class);
.getBean(ServletRegistrationBean.class); assertThat(registrationBean.getInitParameters()).containsEntry("key1",
assertThat(registrationBean.getInitParameters()).containsEntry("key1", "value1"); "value1");
assertThat(registrationBean.getInitParameters()).containsEntry("key2", "value2"); assertThat(registrationBean.getInitParameters()).containsEntry("key2",
} "value2");
});
private void load(Class<?> config, String... environment) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
TestPropertyValues.of(environment).applyTo(context);
context.register(config);
context.refresh();
this.context = context;
} }
} }

@ -18,12 +18,9 @@ package org.springframework.boot.test.autoconfigure.jdbc;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.context.ContextLoader;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
@ -36,52 +33,33 @@ import static org.assertj.core.api.Assertions.assertThat;
* Tests for {@link TestDatabaseAutoConfiguration}. * Tests for {@link TestDatabaseAutoConfiguration}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Andy Wilkinson
*/ */
public class TestDatabaseAutoConfigurationTests { public class TestDatabaseAutoConfigurationTests {
private ConfigurableApplicationContext context; private final ContextLoader contextLoader = new ContextLoader()
.autoConfig(TestDatabaseAutoConfiguration.class);
@After
public void closeContext() {
if (this.context != null) {
this.context.close();
}
}
@Test @Test
public void replaceWithNoDataSourceAvailable() { public void replaceWithNoDataSourceAvailable() {
load(null); this.contextLoader.load(context -> {
assertThat(this.context.getBeansOfType(DataSource.class)).isEmpty(); assertThat(context.getBeansOfType(DataSource.class)).isEmpty();
});
} }
@Test @Test
public void replaceWithUniqueDatabase() { public void replaceWithUniqueDatabase() {
load(ExistingDataSourceConfiguration.class); this.contextLoader.config(ExistingDataSourceConfiguration.class).load(context -> {
DataSource datasource = this.context.getBean(DataSource.class); DataSource datasource = context.getBean(DataSource.class);
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
jdbcTemplate.execute("create table example (id int, name varchar);"); jdbcTemplate.execute("create table example (id int, name varchar);");
try (ConfigurableApplicationContext anotherContext = doLoad( this.contextLoader.load(anotherContext -> {
ExistingDataSourceConfiguration.class)) { DataSource anotherDatasource = anotherContext.getBean(DataSource.class);
DataSource anotherDatasource = anotherContext.getBean(DataSource.class); JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource);
JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource); anotherJdbcTemplate
anotherJdbcTemplate.execute("create table example (id int, name varchar);"); .execute("create table example (id int, name varchar);");
} });
} });
private void load(Class<?> config, String... environment) {
this.context = doLoad(config, environment);
}
private ConfigurableApplicationContext doLoad(Class<?> config,
String... environment) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
if (config != null) {
ctx.register(config);
}
ctx.register(TestDatabaseAutoConfiguration.class);
TestPropertyValues.of(environment).applyTo(ctx);
ctx.refresh();
return ctx;
} }
@Configuration @Configuration

@ -18,17 +18,14 @@ package org.springframework.boot.test.autoconfigure.orm.jpa;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration;
import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.context.ContextLoader;
import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -40,26 +37,19 @@ import static org.mockito.Mockito.mock;
* available. * available.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Andy Wilkinson
*/ */
@RunWith(ModifiedClassPathRunner.class) @RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "h2-*.jar", "hsqldb-*.jar", "derby-*.jar" }) @ClassPathExclusions({ "h2-*.jar", "hsqldb-*.jar", "derby-*.jar" })
public class TestDatabaseAutoConfigurationNoEmbeddedTests { public class TestDatabaseAutoConfigurationNoEmbeddedTests {
private ConfigurableApplicationContext context; private final ContextLoader contextLoader = new ContextLoader()
.config(ExistingDataSourceConfiguration.class)
@After .autoConfig(TestDatabaseAutoConfiguration.class);
public void closeContext() {
if (this.context != null) {
this.context.close();
}
}
@Test @Test
public void applyAnyReplace() { public void applyAnyReplace() {
try { this.contextLoader.loadAndFail(BeanCreationException.class, ex -> {
load(ExistingDataSourceConfiguration.class);
}
catch (BeanCreationException ex) {
String message = ex.getMessage(); String message = ex.getMessage();
assertThat(message).contains( assertThat(message).contains(
"Failed to replace DataSource with an embedded database for tests."); "Failed to replace DataSource with an embedded database for tests.");
@ -68,30 +58,16 @@ public class TestDatabaseAutoConfigurationNoEmbeddedTests {
+ "classpath"); + "classpath");
assertThat(message).contains( assertThat(message).contains(
"or tune the replace attribute of @AutoconfigureTestDatabase."); "or tune the replace attribute of @AutoconfigureTestDatabase.");
} });
} }
@Test @Test
public void applyNoReplace() { public void applyNoReplace() {
load(ExistingDataSourceConfiguration.class, "spring.test.database.replace=NONE"); this.contextLoader.env("spring.test.database.replace=NONE").load(context -> {
assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1); assertThat(context.getBeansOfType(DataSource.class)).hasSize(1);
assertThat(this.context.getBean(DataSource.class)) assertThat(context.getBean(DataSource.class))
.isSameAs(this.context.getBean("myCustomDataSource")); .isSameAs(context.getBean("myCustomDataSource"));
} });
public void load(Class<?> config, String... environment) {
this.context = doLoad(config, environment);
}
public ConfigurableApplicationContext doLoad(Class<?> config, String... environment) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
if (config != null) {
ctx.register(config);
}
ctx.register(TestDatabaseAutoConfiguration.class);
TestPropertyValues.of(environment).applyTo(ctx);
ctx.refresh();
return ctx;
} }
@Configuration @Configuration

@ -26,13 +26,19 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier;
import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.web.reactive.context.GenericReactiveWebApplicationContext;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.AnnotationConfigRegistry;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.mock.web.MockServletContext;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -96,6 +102,8 @@ public class ContextLoader {
private final LinkedList<Class<?>> autoConfigurations = new LinkedList<>(); private final LinkedList<Class<?>> autoConfigurations = new LinkedList<>();
private Supplier<ConfigurableApplicationContext> contextSupplier = () -> new AnnotationConfigApplicationContext();
private ClassLoader classLoader; private ClassLoader classLoader;
/** /**
@ -182,6 +190,32 @@ public class ContextLoader {
return this; return this;
} }
/**
* Configures the loader to create an {@link ApplicationContext} suitable for use in a
* reactive web application.
* @return this instance
*/
public ContextLoader webReactive() {
this.contextSupplier = () -> {
return new GenericReactiveWebApplicationContext();
};
return this;
}
/**
* Configures the loader to create an {@link ApplicationContext} suitable for use in a
* servlet web application.
* @return this instance
*/
public ContextLoader webServlet() {
this.contextSupplier = () -> {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
return context;
};
return this;
}
/** /**
* Create and refresh a new {@link ApplicationContext} based on the current state of * Create and refresh a new {@link ApplicationContext} based on the current state of
* this loader. The context is consumed by the specified {@link ContextConsumer} and * this loader. The context is consumed by the specified {@link ContextConsumer} and
@ -239,25 +273,26 @@ public class ContextLoader {
} }
private ConfigurableApplicationContext createApplicationContext() { private ConfigurableApplicationContext createApplicationContext() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ConfigurableApplicationContext context = ContextLoader.this.contextSupplier.get();
if (this.classLoader != null) { if (this.classLoader != null) {
ctx.setClassLoader(this.classLoader); ((DefaultResourceLoader) context).setClassLoader(this.classLoader);
} }
if (!ObjectUtils.isEmpty(this.env)) { if (!ObjectUtils.isEmpty(this.env)) {
TestPropertyValues.of(this.env.toArray(new String[this.env.size()])) TestPropertyValues.of(this.env.toArray(new String[this.env.size()]))
.applyTo(ctx); .applyTo(context);
} }
AnnotationConfigRegistry registry = ((AnnotationConfigRegistry) context);
if (!ObjectUtils.isEmpty(this.userConfigurations)) { if (!ObjectUtils.isEmpty(this.userConfigurations)) {
ctx.register(this.userConfigurations registry.register(this.userConfigurations
.toArray(new Class<?>[this.userConfigurations.size()])); .toArray(new Class<?>[this.userConfigurations.size()]));
} }
if (!ObjectUtils.isEmpty(this.autoConfigurations)) { if (!ObjectUtils.isEmpty(this.autoConfigurations)) {
LinkedHashSet<Class<?>> linkedHashSet = new LinkedHashSet<>( LinkedHashSet<Class<?>> linkedHashSet = new LinkedHashSet<>(
this.autoConfigurations); this.autoConfigurations);
ctx.register( registry.register(
linkedHashSet.toArray(new Class<?>[this.autoConfigurations.size()])); linkedHashSet.toArray(new Class<?>[this.autoConfigurations.size()]));
} }
return ctx; return context;
} }
/** /**

Loading…
Cancel
Save