Rework ApplicationContext test helper

Rename `ContextLoader` to `ApplicationContextTester` and provide
distinct subclasses for standard, web and reactive application contexts.

Context callbacks now return AssertJ compatible contexts, allowing
tests to run directly on context. For example:

	context.run((loaded) -> assertThat(loaded).hasBean("foo"));

The returned context can now also represent a context that has failed
to start (meaning that the `loadAndFail` methods are no longer needed):

	context.run((loaded) -> assertThat(loaded).hasFailed());

Configuration classes are loaded via the recently introduced
`Configurations` class. This means that the tester no longer needs to
be directly aware of auto-configuration concepts.

See gh-9634
This commit is contained in:
Phillip Webb
2017-07-19 08:58:02 -07:00
parent c6f55ef46d
commit 24d086066b
24 changed files with 2219 additions and 889 deletions

View File

@@ -0,0 +1,194 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import java.util.UUID;
import com.google.gson.Gson;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.context.annotation.UserConfigurations;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
/**
* Abstract tests for {@link AbstractApplicationContextTester} implementations.
*
* @param <T> The tester type
* @param <C> the context type
* @param <A> the assertable context type
* @author Stephane Nicoll
* @author Phillip Webb
*/
public abstract class AbstractApplicationContextTesterTests<T extends AbstractApplicationContextTester<T, C, A>, C extends ConfigurableApplicationContext, A extends AssertProviderApplicationContext<C>> {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void runWithSystemPropertiesShouldSetAndRemoveProperties() {
String key = "test." + UUID.randomUUID().toString();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value").run(loaded -> {
assertThat(System.getProperties()).containsEntry(key, "value");
});
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
public void runWithSystemPropertiesWhenContextFailsShouldRemoveProperties()
throws Exception {
String key = "test." + UUID.randomUUID().toString();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.withUserConfiguration(FailingConfig.class).run(loaded -> {
assertThat(loaded).hasFailed();
});
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
public void runWithSystemPropertiesShouldRestoreOriginalProperties()
throws Exception {
String key = "test." + UUID.randomUUID().toString();
System.setProperty(key, "value");
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=newValue").run(loaded -> {
assertThat(System.getProperties()).containsEntry(key, "newValue");
});
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
System.clearProperty(key);
}
}
@Test
public void runWithSystemPropertiesWhenValueIsNullShouldRemoveProperty()
throws Exception {
String key = "test." + UUID.randomUUID().toString();
System.setProperty(key, "value");
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperty(key, null).run(loaded -> {
assertThat(System.getProperties()).doesNotContainKey(key);
});
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
System.clearProperty(key);
}
}
@Test
public void runWithMultiplePropertyValuesShouldAllAllValues() throws Exception {
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2")
.run(loaded -> {
Environment environment = loaded.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
});
}
@Test
public void runWithPropertyValuesWhenHasExistingShouldReplaceValue()
throws Exception {
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2")
.run(loaded -> {
Environment environment = loaded.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
}
@Test
public void runWithConfigurationsShouldRegisterConfigurations() throws Exception {
get().withUserConfiguration(FooConfig.class)
.run((loaded) -> assertThat(loaded).hasBean("foo"));
}
@Test
public void runWithMultipleConfigurationsShouldRegisterAllConfigurations()
throws Exception {
get().withUserConfiguration(FooConfig.class)
.withConfiguration(UserConfigurations.of(BarConfig.class))
.run((loaded) -> assertThat(loaded).hasBean("foo").hasBean("bar"));
}
@Test
public void runWithFailedContextShouldReturnFailedAssertableContext()
throws Exception {
get().withUserConfiguration(FailingConfig.class)
.run((loaded) -> assertThat(loaded).hasFailed());
}
@Test
public void runWithClassLoaderShouldSetClassLoader() throws Exception {
get().withClassLoader(
new HidePackagesClassLoader(Gson.class.getPackage().getName()))
.run((loaded) -> {
try {
ClassUtils.forName(Gson.class.getName(), loaded.getClassLoader());
fail("Should have thrown a ClassNotFoundException");
}
catch (ClassNotFoundException e) {
// expected
}
});
}
protected abstract T get();
@Configuration
static class FailingConfig {
@Bean
public String foo() {
throw new IllegalStateException("Failed");
}
}
@Configuration
static class FooConfig {
@Bean
public String foo() {
return "foo";
}
}
@Configuration
static class BarConfig {
@Bean
public String bar() {
return "bar";
}
}
}

View File

@@ -0,0 +1,314 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ApplicationContextAssert}.
*
* @author Phillip Webb
*/
public class ApplicationContextAssertTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private StaticApplicationContext context = new StaticApplicationContext();
private RuntimeException failure = new RuntimeException();
@Test
public void createWhenApplicationContextIsNullShouldThrowException()
throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ApplicationContext must not be null");
new ApplicationContextAssert<>(null, null);
}
@Test
public void createWhenHasApplicationContextShouldSetActual() throws Exception {
assertThat(getAssert(this.context).getSourceApplicationContext())
.isSameAs(this.context);
}
@Test
public void createWhenHasExceptionShouldSetFailure() throws Exception {
assertThat(getAssert(this.failure)).getFailure().isSameAs(this.failure);
}
@Test
public void hasBeanWhenHasBeanShouldPass() throws Exception {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).hasBean("foo");
}
@Test
public void hasBeanWhenHasNoBeanShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("no such bean");
assertThat(getAssert(this.context)).hasBean("foo");
}
@Test
public void hasBeanWhenNotStartedShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).hasBean("foo");
}
@Test
public void hasSingleBeanWhenHasSingleBeanShouldPass() throws Exception {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).hasSingleBean(Foo.class);
}
@Test
public void hasSingleBeanWhenHasNoBeansShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("no beans of that type");
assertThat(getAssert(this.context)).hasSingleBean(Foo.class);
}
@Test
public void hasSingleBeanWhenHasMultipleShouldFail() throws Exception {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found:");
assertThat(getAssert(this.context)).hasSingleBean(Foo.class);
}
@Test
public void hasSingleBeanWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).hasSingleBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfTypeWhenHasNoBeanOfTypeShouldPass() throws Exception {
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found");
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class);
}
@Test
public void doesNotHaveBeanOfNameWhenHasNoBeanOfTypeShouldPass() throws Exception {
assertThat(getAssert(this.context)).doesNotHaveBean("foo");
}
@Test
public void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found");
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).doesNotHaveBean("foo");
}
@Test
public void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).doesNotHaveBean("foo");
}
@Test
public void getBeanNamesWhenHasNamesShouldReturnNamesAssert() throws Exception {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo",
"bar");
}
@Test
public void getBeanNamesWhenHasNoNamesShouldReturnEmptyAssert() throws Exception {
assertThat(getAssert(this.context)).getBeanNames(Foo.class).isEmpty();
}
@Test
public void getBeanNamesWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).doesNotHaveBean("foo");
}
@Test
public void getBeanOfTypeWhenHasBeanShouldReturnBeanAssert() throws Exception {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean(Foo.class).isNotNull();
}
@Test
public void getBeanOfTypeWhenHasNoBeanShouldReturnNullAssert() throws Exception {
assertThat(getAssert(this.context)).getBean(Foo.class).isNull();
}
@Test
public void getBeanOfTypeWhenHasMultipleBeansShouldFail() throws Exception {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("but found");
assertThat(getAssert(this.context)).getBean(Foo.class);
}
@Test
public void getBeanOfTypeWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).getBean(Foo.class);
}
@Test
public void getBeanOfNameWhenHasBeanShouldReturnBeanAssert() throws Exception {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean("foo").isNotNull();
}
@Test
public void getBeanOfNameWhenHasNoBeanOfNameShouldReturnNullAssert()
throws Exception {
assertThat(getAssert(this.context)).getBean("foo").isNull();
}
@Test
public void getBeanOfNameWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).getBean("foo");
}
@Test
public void getBeanOfNameAndTypeWhenHasBeanShouldReturnBeanAssert() throws Exception {
this.context.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean("foo", Foo.class).isNotNull();
}
@Test
public void getBeanOfNameAndTypeWhenHasNoBeanOfNameShouldReturnNullAssert()
throws Exception {
assertThat(getAssert(this.context)).getBean("foo", Foo.class).isNull();
}
@Test
public void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail()
throws Exception {
this.context.registerSingleton("foo", Foo.class);
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("of type");
assertThat(getAssert(this.context)).getBean("foo", String.class);
}
@Test
public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).getBean("foo", Foo.class);
}
@Test
public void getBeansWhenHasBeansShouldReturnMapAssert() throws Exception {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
.containsKeys("foo", "bar");
}
@Test
public void getBeansWhenHasNoBeansShouldReturnEmptyMapAssert() throws Exception {
assertThat(getAssert(this.context)).getBeans(Foo.class).isEmpty();
}
@Test
public void getBeansWhenFailedToStartShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("failed to start");
assertThat(getAssert(this.failure)).getBeans(Foo.class);
}
@Test
public void getFailureWhenFailedShouldReturnFailure() throws Exception {
assertThat(getAssert(this.failure)).getFailure().isSameAs(this.failure);
}
@Test
public void getFailureWhenDidNotFailShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("context started");
assertThat(getAssert(this.context)).getFailure();
}
@Test
public void hasFailedWhenFailedShouldPass() throws Exception {
assertThat(getAssert(this.failure)).hasFailed();
}
@Test
public void hasFailedWhenNotFailedShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have failed");
assertThat(getAssert(this.context)).hasFailed();
}
@Test
public void hasNotFailedWhenFailedShouldFail() throws Exception {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have not failed");
assertThat(getAssert(this.failure)).hasNotFailed();
}
@Test
public void hasNotFailedWhenNotFailedShouldPass() throws Exception {
assertThat(getAssert(this.context)).hasNotFailed();
}
private AssertableApplicationContext getAssert(
ConfigurableApplicationContext applicationContext) {
return AssertableApplicationContext.get(() -> applicationContext);
}
private AssertableApplicationContext getAssert(RuntimeException failure) {
return AssertableApplicationContext.get(() -> {
throw failure;
});
}
private static class Foo {
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import org.springframework.context.ConfigurableApplicationContext;
/**
* Tests for {@link ApplicationContextTester}.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
public class ApplicationContextTesterTests extends
AbstractApplicationContextTesterTests<ApplicationContextTester, ConfigurableApplicationContext, AssertableApplicationContext> {
@Override
protected ApplicationContextTester get() {
return new ApplicationContextTester();
}
}

View File

@@ -0,0 +1,245 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import java.util.function.Supplier;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link AssertProviderApplicationContext} and
* {@link AssertProviderApplicationContextInvocationHandler}.
*
* @author Phillip Webb
*/
public class AssertProviderApplicationContextTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private ConfigurableApplicationContext mockContext;
private RuntimeException startupFailure;
private Supplier<ApplicationContext> mockContextSupplier;
private Supplier<ApplicationContext> startupFailureSupplier;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.startupFailure = new RuntimeException();
this.mockContextSupplier = () -> this.mockContext;
this.startupFailureSupplier = () -> {
throw this.startupFailure;
};
}
@Test
public void getWhenTypeIsNullShouldThrowExecption() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
AssertProviderApplicationContext.get(null, ApplicationContext.class,
this.mockContextSupplier);
}
@Test
public void getWhenTypeIsClassShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
AssertProviderApplicationContext.get(null, ApplicationContext.class,
this.mockContextSupplier);
}
@Test
public void getWhenContextTypeIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must be an interface");
AssertProviderApplicationContext.get(
TestAssertProviderApplicationContextClass.class, ApplicationContext.class,
this.mockContextSupplier);
}
@Test
public void getWhenContextTypeIsClassShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ContextType must not be null");
AssertProviderApplicationContext.get(TestAssertProviderApplicationContext.class,
null, this.mockContextSupplier);
}
@Test
public void getWhenSupplierIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ContextType must be an interface");
AssertProviderApplicationContext.get(TestAssertProviderApplicationContext.class,
StaticApplicationContext.class, this.mockContextSupplier);
}
@Test
public void getWhenContextStartsShouldReturnProxyThatCallsRealMethods()
throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat((Object) context).isNotNull();
context.getBean("foo");
verify(this.mockContext).getBean("foo");
}
@Test
public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions()
throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.startupFailureSupplier);
assertThat((Object) context).isNotNull();
expectStartupFailure();
context.getBean("foo");
}
@Test
public void getSourceContextWhenContextStartsShouldReturnSourceContext()
throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext);
}
@Test
public void getSourceContextWhenContextFailsShouldThrowException() throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.startupFailureSupplier);
expectStartupFailure();
context.getSourceApplicationContext();
}
@Test
public void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext()
throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getSourceApplicationContext(ApplicationContext.class))
.isSameAs(this.mockContext);
}
@Test
public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException()
throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.startupFailureSupplier);
expectStartupFailure();
context.getSourceApplicationContext(ApplicationContext.class);
}
@Test
public void getStartupFailureWhenContextStartsShouldReturnNull() throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getStartupFailure()).isNull();
}
@Test
public void getStartupFailureWhenContextFailsToStartShouldReturnException()
throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.startupFailureSupplier);
assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure);
}
@Test
public void assertThatWhenContextStartsShouldReturnAssertions() throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isNull();
}
@Test
public void assertThatWhenContextFailsShouldReturnAssertions() throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isSameAs(this.startupFailure);
}
@Test
public void toStringWhenContextStartsShouldReturnSimpleString() throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.toString())
.startsWith(
"Started application org.springframework.context.ConfigurableApplicationContext$MockitoMock")
.endsWith("[id=<null>,applicationName=<null>,beanDefinitionCount=0]");
}
@Test
public void toStringWhenContextFailsToStartShouldReturnSimpleString()
throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.startupFailureSupplier);
assertThat(context.toString()).isEqualTo("Unstarted application context "
+ "org.springframework.context.ApplicationContext"
+ "[startupFailure=java.lang.RuntimeException]");
}
@Test
public void closeShouldCloseContext() throws Exception {
AssertProviderApplicationContext<ApplicationContext> context = get(
this.mockContextSupplier);
context.close();
verify(this.mockContext).close();
}
private void expectStartupFailure() {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("failed to start");
this.thrown.expectCause(equalTo(this.startupFailure));
}
private AssertProviderApplicationContext<ApplicationContext> get(
Supplier<ApplicationContext> contextSupplier) {
return AssertProviderApplicationContext.get(
TestAssertProviderApplicationContext.class, ApplicationContext.class,
contextSupplier);
}
private interface TestAssertProviderApplicationContext
extends AssertProviderApplicationContext<ApplicationContext> {
}
private abstract static class TestAssertProviderApplicationContextClass
implements TestAssertProviderApplicationContext {
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link AssertableApplicationContext}.
*
* @author Phillip Webb
* @see AssertProviderApplicationContextTests
*/
public class AssertableApplicationContextTests {
@Test
public void getShouldReturnProxy() {
AssertableApplicationContext context = AssertableApplicationContext
.get(() -> mock(ConfigurableApplicationContext.class));
assertThat(context).isInstanceOf(ConfigurableApplicationContext.class);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import org.junit.Test;
import org.springframework.boot.web.reactive.context.ConfigurableReactiveWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link AssertableReactiveWebApplicationContext}.
*
* @author Phillip Webb
* @see AssertProviderApplicationContextTests
*/
public class AssertableReactiveWebApplicationContextTests {
@Test
public void getShouldReturnProxy() {
AssertableReactiveWebApplicationContext context = AssertableReactiveWebApplicationContext
.get(() -> mock(ConfigurableReactiveWebApplicationContext.class));
assertThat(context).isInstanceOf(ConfigurableReactiveWebApplicationContext.class);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import org.junit.Test;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link AssertableWebApplicationContext}.
*
* @author Phillip Webb
* @see AssertProviderApplicationContextTests
*/
public class AssertableWebApplicationContextTests {
@Test
public void getShouldReturnProxy() {
AssertableWebApplicationContext context = AssertableWebApplicationContext
.get(() -> mock(ConfigurableWebApplicationContext.class));
assertThat(context).isInstanceOf(ConfigurableWebApplicationContext.class);
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import org.springframework.boot.web.reactive.context.ConfigurableReactiveWebApplicationContext;
/**
* Tests for {@link ReactiveWebApplicationContextTester}.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
public class ReactiveWebApplicationContextTesterTests extends
AbstractApplicationContextTesterTests<ReactiveWebApplicationContextTester, ConfigurableReactiveWebApplicationContext, AssertableReactiveWebApplicationContext> {
@Override
protected ReactiveWebApplicationContextTester get() {
return new ReactiveWebApplicationContextTester();
}
}

View File

@@ -1,258 +0,0 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import java.util.UUID;
import com.google.gson.Gson;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/**
* Tests for {@link StandardContextLoader}.
*
* @author Stephane Nicoll
*/
public class StandardContextLoaderTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final StandardContextLoader contextLoader = new StandardContextLoader(
AnnotationConfigApplicationContext::new);
@Test
public void systemPropertyIsSetAndRemoved() {
String key = "test." + UUID.randomUUID().toString();
assertThat(System.getProperties().containsKey(key)).isFalse();
this.contextLoader.systemProperty(key, "value").load(context -> {
assertThat(System.getProperties().containsKey(key)).isTrue();
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
});
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
public void systemPropertyIsRemovedIfContextFailed() {
String key = "test." + UUID.randomUUID().toString();
assertThat(System.getProperties().containsKey(key)).isFalse();
this.contextLoader.systemProperty(key, "value").config(ConfigC.class)
.loadAndFail(e -> {
});
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
public void systemPropertyIsRestoredToItsOriginalValue() {
String key = "test." + UUID.randomUUID().toString();
System.setProperty(key, "value");
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
this.contextLoader.systemProperty(key, "newValue").load(context -> {
assertThat(System.getProperties().getProperty(key)).isEqualTo("newValue");
});
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
System.clearProperty(key);
}
}
@Test
public void systemPropertyCanBeSetToNullValue() {
String key = "test." + UUID.randomUUID().toString();
assertThat(System.getProperties().containsKey(key)).isFalse();
this.contextLoader.systemProperty(key, "value").systemProperty(key, null)
.load(context -> {
assertThat(System.getProperties().containsKey(key)).isFalse();
});
}
@Test
public void systemPropertyNeedNonNullKey() {
this.thrown.expect(IllegalArgumentException.class);
this.contextLoader.systemProperty(null, "value");
}
@Test
public void envIsAdditive() {
this.contextLoader.env("test.foo=1").env("test.bar=2").load(context -> {
ConfigurableEnvironment environment = context
.getBean(ConfigurableEnvironment.class);
assertThat(environment.getProperty("test.foo", Integer.class)).isEqualTo(1);
assertThat(environment.getProperty("test.bar", Integer.class)).isEqualTo(2);
});
}
@Test
public void envOverridesExistingKey() {
this.contextLoader.env("test.foo=1").env("test.foo=2")
.load(context -> assertThat(context.getBean(ConfigurableEnvironment.class)
.getProperty("test.foo", Integer.class)).isEqualTo(2));
}
@Test
public void configurationIsProcessedInOrder() {
this.contextLoader.config(ConfigA.class, AutoConfigA.class).load(
context -> assertThat(context.getBean("a")).isEqualTo("autoconfig-a"));
}
@Test
public void configurationIsProcessedBeforeAutoConfiguration() {
this.contextLoader.autoConfig(AutoConfigA.class).config(ConfigA.class).load(
context -> assertThat(context.getBean("a")).isEqualTo("autoconfig-a"));
}
@Test
public void configurationIsAdditive() {
this.contextLoader.config(AutoConfigA.class).config(AutoConfigB.class)
.load(context -> {
assertThat(context.containsBean("a")).isTrue();
assertThat(context.containsBean("b")).isTrue();
});
}
@Test
public void autoConfigureFirstIsAppliedProperly() {
this.contextLoader.autoConfig(ConfigA.class).autoConfigFirst(AutoConfigA.class)
.load(context -> assertThat(context.getBean("a")).isEqualTo("a"));
}
@Test
public void autoConfigureFirstWithSeveralConfigsIsAppliedProperly() {
this.contextLoader.autoConfig(ConfigA.class, ConfigB.class)
.autoConfigFirst(AutoConfigA.class, AutoConfigB.class).load(context -> {
assertThat(context.getBean("a")).isEqualTo("a");
assertThat(context.getBean("b")).isEqualTo(1);
});
}
@Test
public void autoConfigurationIsAdditive() {
this.contextLoader.autoConfig(AutoConfigA.class).autoConfig(AutoConfigB.class)
.load(context -> {
assertThat(context.containsBean("a")).isTrue();
assertThat(context.containsBean("b")).isTrue();
});
}
@Test
public void loadAndFailWithExpectedException() {
this.contextLoader.config(ConfigC.class).loadAndFail(BeanCreationException.class,
ex -> assertThat(ex.getMessage())
.contains("Error creating bean with name 'c'"));
}
@Test
public void loadAndFailWithWrongException() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("Wrong application context failure exception");
this.contextLoader.config(ConfigC.class)
.loadAndFail(IllegalArgumentException.class, ex -> {
});
}
@Test
public void classLoaderIsUsed() {
this.contextLoader
.classLoader(
new HidePackagesClassLoader(Gson.class.getPackage().getName()))
.load(context -> {
try {
ClassUtils.forName(Gson.class.getName(),
context.getClassLoader());
fail("Should have thrown a ClassNotFoundException");
}
catch (ClassNotFoundException e) {
// expected
}
});
}
@Test
public void assertionErrorsAreAvailableAsIs() {
try {
this.contextLoader.load(context -> {
fail("This is expected");
});
}
catch (AssertionError ex) {
assertThat(ex.getMessage()).isEqualTo("This is expected");
}
}
@Configuration
static class ConfigA {
@Bean
public String a() {
return "a";
}
}
@Configuration
static class ConfigB {
@Bean
public Integer b() {
return 1;
}
}
@Configuration
static class AutoConfigA {
@Bean
public String a() {
return "autoconfig-a";
}
}
@Configuration
static class AutoConfigB {
@Bean
public Integer b() {
return 42;
}
}
@Configuration
static class ConfigC {
@Bean
public String c(Integer value) {
return String.valueOf(value);
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2012-2017 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import org.junit.Test;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link WebApplicationContextTester}.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
public class WebApplicationContextTesterTests extends
AbstractApplicationContextTesterTests<WebApplicationContextTester, ConfigurableWebApplicationContext, AssertableWebApplicationContext> {
@Test
public void contextShouldHaveMockServletContext() throws Exception {
get().run((loaded) -> assertThat(loaded.getServletContext())
.isInstanceOf(MockServletContext.class));
}
@Override
protected WebApplicationContextTester get() {
return new WebApplicationContextTester();
}
}