Fail fast if @WebAppConfiguration is used with a non-mock web environement
@WebAppConfiguration expects a mock web environment. If it is used in conjuction with @SpringBootTest configured with a RANDOM_PORT or DEFINED_PORT web environment a null pointer exception occurs as an assumption that's made by MockServerContainerContextCustomizer doesn't hold true in a non-mock web environment. This commit updates SpringBootTestContextBootstrap to detect the illegal configuration combination and fail fast, advising the user to remove @WebAppConfiguration or reconfigure @SpringBootTest. Closes gh-6795
This commit is contained in:
@@ -16,6 +16,7 @@
|
||||
|
||||
package org.springframework.boot.test.context;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -75,6 +76,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
@Override
|
||||
public TestContext buildTestContext() {
|
||||
TestContext context = super.buildTestContext();
|
||||
verifyConfiguration(context.getTestClass());
|
||||
WebEnvironment webEnvironment = getWebEnvironment(context.getTestClass());
|
||||
if (webEnvironment == WebEnvironment.MOCK && hasWebEnvironmentClasses()) {
|
||||
context.setAttribute(ACTIVATE_SERVLET_LISTENER, true);
|
||||
@@ -261,6 +263,24 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
return AnnotatedElementUtils.getMergedAnnotation(testClass, SpringBootTest.class);
|
||||
}
|
||||
|
||||
protected void verifyConfiguration(Class<?> testClass) {
|
||||
SpringBootTest springBootTest = getAnnotation(testClass);
|
||||
if (springBootTest != null
|
||||
&& (springBootTest.webEnvironment() == WebEnvironment.DEFINED_PORT
|
||||
|| springBootTest.webEnvironment() == WebEnvironment.RANDOM_PORT)
|
||||
&& getAnnotation(WebAppConfiguration.class, testClass) != null) {
|
||||
throw new IllegalStateException("@WebAppConfiguration should only be used "
|
||||
+ "with @SpringBootTest when @SpringBootTest is configured with a "
|
||||
+ "mock web environment. Please remove @WebAppConfiguration or "
|
||||
+ "reconfigure @SpringBootTest.");
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Annotation> T getAnnotation(Class<T> annotationType,
|
||||
Class<?> testClass) {
|
||||
return AnnotatedElementUtils.getMergedAnnotation(testClass, annotationType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@link MergedContextConfiguration} with different classes.
|
||||
* @param mergedConfig the source config
|
||||
|
||||
Reference in New Issue
Block a user