Support servlet listener activate attribute

Add a ServletTestExecutionListener.ACTIVATE_LISTENER attribute which
can be set on the TestContext to trigger activation of the listener
even if a `@WebAppConfiguration` is not present.

Issue: SPR-14035
This commit is contained in:
Phillip Webb
2016-03-09 23:33:45 -08:00
committed by Sam Brannen
parent 8ca6a18dae
commit bb590db396
2 changed files with 31 additions and 5 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -98,6 +98,16 @@ public class ServletTestExecutionListener extends AbstractTestExecutionListener
public static final String CREATED_BY_THE_TESTCONTEXT_FRAMEWORK = Conventions.getQualifiedAttributeName(
ServletTestExecutionListener.class, "createdByTheTestContextFramework");
/**
* Attribute name for a {@link TestContext} attribute which indicates that
* that the {@link ServletTestExecutionListener} should be activated. When
* not specified activation occurs when the {@linkplain TestContext#getTestClass()
* test class} is annotated with {@link WebAppConfiguration @WebAppConfiguration}.
* @since 4.4
*/
public static final String ACTIVATE_LISTENER = Conventions.getQualifiedAttributeName(
ServletTestExecutionListener.class, "webApplicationConfiguration");
private static final Log logger = LogFactory.getLog(ServletTestExecutionListener.class);
@@ -167,8 +177,9 @@ public class ServletTestExecutionListener extends AbstractTestExecutionListener
testContext.removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
}
private boolean notAnnotatedWithWebAppConfiguration(TestContext testContext) {
return AnnotationUtils.findAnnotation(testContext.getTestClass(), WebAppConfiguration.class) == null;
private boolean isActivated(TestContext testContext) {
return (Boolean.TRUE.equals(testContext.getAttribute(ACTIVATE_LISTENER))
|| AnnotationUtils.findAnnotation(testContext.getTestClass(), WebAppConfiguration.class) != null);
}
private boolean alreadyPopulatedRequestContextHolder(TestContext testContext) {
@@ -176,7 +187,7 @@ public class ServletTestExecutionListener extends AbstractTestExecutionListener
}
private void setUpRequestContextIfNecessary(TestContext testContext) {
if (notAnnotatedWithWebAppConfiguration(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
return;
}