Repository navigation
Description
Geoff Metselaar opened SPR-5243 and commented
Status Quo
When the Spring TestContext Framework was introduced in Spring 2.5, it supported loading an ApplicationContext from either XML or Java Properties files. Spring 3.1 introduced support for loading an ApplicationContext from annotated classes (e.g., @Configuration classes).
The underlying implementation for the existing support creates a GenericApplicationContext; however, a GenericApplicationContext is not suitable for testing a web application since a web application relies on an implementation of WebApplicationContext (WAC).
In order to integration test Spring-powered web applications the Spring TestContext Framework needs to be able to load a WebApplicationContext, either from XML configuration files or from annotated classes. Furthermore, the ServletContext used by such a WAC needs to be configurable within tests, and common context hierarchies must be supported (e.g., root and dispatcher WACs in a parent-child relationship).
Original Author's Description
While writing some MVC integration tests, context errors were thrown when loading an XmlViewResolver and when attempting to recover command object property validation errors using the RequestContext. The reason is that each of these requires access to a WebApplicationContext, not a GenericApplicationContext which the TestContext framework makes available by default.
Goals
- Introduce an annotation that allows developers to configure a mock
ServletContextfrom within integration tests. - Introduce
SmartContextLoadersthat can loadWebApplicationContextsfrom either XML or annotated classes, using the configured mockServletContext. - Provide a means for developers to access the mocks for the
HttpServletRequestandHttpServletResponseobjects and ensure that thread-local state in Spring MVC is kept in sync with these mock objects. - Ensure that metadata used to create the
WebApplicationContext(e.g.,ServletContextpath) is used to define the unique application context cache key.
Deliverables
- Implement a
SmartContextLoaderthat loads aWebApplicationContextfrom XML resource locations defined via@ContextConfiguration - Implement a
SmartContextLoaderthat loads aWebApplicationContextfrom annotated classes defined via@ContextConfiguration - Introduce a new class-level
@WebAppConfigurationannotation that allows for configuration of theServletContextbase resource path, using Spring'sResourceabstraction- see
ContextMockMvcBuilder.configureWebAppRootDir()fromspring-test-mvc - the base path must be filesystem-based by default, in contrast to the
locationsattribute in@ContextConfigurationwhich is classpath-based - the base path should default to "src/main/webapp", which follows the Maven convention
- determine if
@WebAppConfigurationshould be inherited (i.e., annotated with@Inherited), keeping in mind that the top-level context in an EAR would not be a WAC
- see
- Ensure that the two newly introduced
SmartContextLoaderimplementations create aMockServletContexton demand (i.e., if a root WAC), when the WAC is loaded, and set theMockServletContextas theServletContextin the application contexts that they load - Set a loaded context as the
ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTEin theMockServletContextwhen context hierarchies are not used - Introduce a subclass of
MergedContextConfigurationspecific for web apps (e.g.,WebMergedContextConfiguration) that stores theServletContextbase path- the subclass of MCC must override
equals()andhashCode()to include the metadata that uniquely identifies the resulting WAC for proper context caching - the
buildMergedContextConfiguration()method inContextLoaderUtilswill likely need to instantiate either a standardMergedContextConfigurationor aWebMergedContextConfiguration
- the subclass of MCC must override
- Set up default thread local state via
RequestContextHolderbefore each test method by implementing a new Servlet-specificTestExecutionListener- by using the
MockServletContextalready present in the WAC and by creating aMockHttpServletRequest,MockHttpServletResponse, andServletWebRequestwhich will be set in theRequestContextHolder
- by using the
- Ensure that the
MockServletContext,MockHttpServletRequest,MockHttpServletResponse, andServletWebRequestcan be injected into the test instance (e.g., via@Autowired) - Clean up thread locals after each test method
- Ensure that the Servlet-specific
TestExecutionListeneris configured as a defaultTestExecutionListenerbeforeDependencyInjectionTestExecutionListener - Introduce a new web-specific
DelegatingSmartContextLoaderto incorporate support for theSmartContextLoadertypes introduced in this issue and ensure that the correct delegating loader is picked based on the presence or absence of@WebAppConfiguration - Consider being able to accommodate a future request to support mocks for Spring Portlet MVC
Pseudocode Examples
Root WAC with Injected Mocks
@WebAppConfiguration // path defaults to "file:src/main/webapp"
@ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml")
public class RootWacTests {
@Autowired
private WebApplicationContext wac;
@Autowired
private MockServletContext servletContext;
@Autowired
private MockHttpServletRequest request;
@Autowired
private MockHttpServletResponse response;
@Autowired
private MockHttpSession session;
@Autowired
private ServletWebRequest webRequest;
//...
}
Further Resources
Blogs and Custom Solutions
- http://codinghood.blogspot.com/2009/01/spring-integration-testing-for-web.html
- http://jamesfarrell129.wordpress.com/2011/04/20/integration-testing-for-spring-portlet-mvc/
- http://tedyoung.me/2011/02/14/spring-mvc-integration-testing-controllers/
- http://code.google.com/p/ted-young/source/browse/trunk/blog.spring-mvc-integration-testing/
Forum Discussions
- http://forum.springframework.org/showthread.php?p=210177#post210177
- http://forum.springframework.org/showthread.php?p=210181
- http://forum.springsource.org/showthread.php?t=76744
Affects: 2.5 final, 3.0 GA, 3.1 GA
Attachments:
- web_listener_loader.zip (6.70 kB)
Issue Links:
- Provide support for context hierarchies in the TestContext Framework [SPR-5613] #10284 Provide support for context hierarchies in the TestContext Framework ("depends on")
- Support WebApplicationContext hierarchies in the TestContext Framework [SPR-9863] #14496 Support WebApplicationContext hierarchies in the TestContext Framework ("is depended on by")
- Provide support for session/request scoped beans for integration testing [SPR-4588] #9265 Provide support for session/request scoped beans for integration testing ("is depended on by")
- Document WebApplicationContext support in the TestContext Framework [SPR-9864] #14497 Document WebApplicationContext support in the TestContext Framework ("is depended on by")
- Provide a ContextLoader for WebApplicationContext [SPR-5850] #10519 Provide a ContextLoader for WebApplicationContext ("is duplicated by")
- Provide test ContextLoader for @ContextConfiguration that creates a WebApplicationContext [SPR-5399] #10072 Provide test ContextLoader for
@ContextConfigurationthat creates a WebApplicationContext ("is duplicated by") - Make Spring ContextTest annotation support WebApplicationContext [SPR-4759] #9436 Make Spring ContextTest annotation support WebApplicationContext ("is duplicated by")
- Add first class support for testing Spring MVC applications [SPR-9859] #14492 Add first class support for testing Spring MVC applications
- Introduce bootstrap strategy in the TestContext framework [SPR-9955] #14588 Introduce bootstrap strategy in the TestContext framework
- Release 1.0 spring-test-mvc [SPR-9211] #13849 Release 1.0 spring-test-mvc
- ApplicationContext fails to load in tests using Java-based config and WebMvcConfigurationSupport [SPR-9799] #14432 ApplicationContext fails to load in tests using Java-based config and WebMvcConfigurationSupport ("supersedes")
Referenced from: commits 461d99a, a281bdb, 90c5f22, 9937f84, a73280c, 21ebbb9
30 votes, 29 watchers
Activity
spring-projects-issues commentedon Oct 28, 2008
Narada Sage commented
I would absolutely love this. I've spent a lot of time trying to get this to work. It shouldn't be this difficult. It'd be great if this not uncommon use case was available out of the box. Thanks.
spring-projects-issues commentedon Feb 23, 2011
Gaetan Pitteloud commented
Loading a WebApplicationContext is not a difficult task on its own : you just provide a
@ContextConfiguration.loader that creates a GenericWebApplicationContext. The difficult task is that the basic contract of a WebApplicationContext is that it knows the ServletContext for several reasons.I have built a solution based on a test listener (so-called WebListener) that creates the web environment (based on spring mock classes) : Mock ServletContext, Mock request, response, session. The ServletContext is created once (beforeTestClass) for a test class, and is <i>injected</i> into the ContextLoader (there's no API to do this, thus I had to do it with reflexion, which is the goal of my TestContextUtils class). I have to ensure that the context is not loaded yet, or this trick will not work (I mark it as dirty for that purpose, and also because it might have been loaded by another test class earlier, or will be used by another test class later on).
You will find attached the WebListener and Web ContextLoader that are working together.
The web listener's duty also includes a way to inject the web mocks (ServletContext, request, response, etc.) into test instance variables that are annotated with
@WebResource. I found it quite useful.The WebListener is actually split into an AbstractWebListener and its subclass WebListener because I also implemented a JsfListener with the same semantics, with the only jsf mock lib I found so far : shale-test.
There are tests in the listener that test for the existence of an application context (by looking for a
@ContextConfigurationannotation in the test class hiererchy) : the reason for this is that the web listener may also be used without an application context in place, i.e. only for creating a mock web environment.The mock objects (request, response, session) are shared for other listeners to use thanks to TestContext internal attributes map, which also happens to be useful.
spring-projects-issues commentedon Jun 1, 2011
Stevo Slavić commented
Checkout Spring MVC integration test support Rosen and Arjen have been building @ https://github.com/SpringSource/spring-test-mvc
First heard about it on S2G Forum 2011 Amsterdam, and Spring 3.2 was mentioned as likely target. Not sure if there is separate ticket for this, but I think they are related.
spring-projects-issues commentedon Jun 2, 2011
Rossen Stoyanchev commented
The two might be quite complementary. You could use this to create and initialize a WebApplicationContext once per test fixture and then provide it to the main class of the Spring MVC integration test support.
spring-projects-issues commentedon Jul 18, 2012
Sam Brannen commented
If you are watching this issue, please feel free to participate in the discussion regarding the proposed Deliverables and the corresponding Pseudocode Examples listed in this issue's Description.
Thanks!
Sam
spring-projects-issues commentedon Jul 18, 2012
Gaetan Pitteloud commented
2 comments:
@WebAppConfigurationis present, the WAC should not be cached and reused in next tests that share the same@ContextConfiguration.locations, because the lifespan of its ServletContext is limited to the test class.And 2 questions:
request.isUserInRole(String role)andrequest.getUserPrincipal()return some configurable values ? The idea would be a@Securedannotation on test methods (with username and roles), that defines the security context of a test case.spring-projects-issues commentedon Jul 19, 2012
Sam Brannen commented
Hi Gaetan,
One of the key features of the TestContext framework is caching. Thus the WAC will certainly be cached by default.
Please note that the proposed subclass of
MergedContextConfigurationwill be responsible for ensuring that the MCC uniquely identifies the WAC for proper caching.Why do you say that "the lifespan of its ServletContext is limited to the test class"?
I would argue that the lifespan of the
ServletContextis tied directly to the lifespan of the correspondingWebApplicationContext. Thus if the WAC is used across multiple test classes, it should definitely be cached.If you want to disable caching of a WAC after a particular test class, simply annotate the test class with
@DirtiesContext.How do you propose to inject the mocks if not from a configured WAC?
Are you proposing to just have a custom
TestExecutionListenerfor this purpose?Can you please provide some pseudocode to demonstrate your use case?
No, there is currently no plan to support this, but it is an interesting idea.
So feel free to create a separate JIRA issue to request it.
The code needed to support the features in this issue will be integrated in the TestContext framework, tentatively including two
SmartContextLoaderimplementations, a subclass ofMergedContextConfiguration, aTestExecutionListener, and an annotation.Regards,
Sam
spring-projects-issues commentedon Jul 20, 2012
Gaetan Pitteloud commented
Hi Sam,
Thanks for the reply and explanations.
Regarding caching, I was thinking about a first test with a plain ApplicationContext and a second test with a WebApplicationContext, both defined with similar xml locations. Using current caching facility (key=xml locations), both contexts would be stored under same key.
But this is now OK as long as the context cache key contains WAC and ServletContext info.
You're right, the lifespan of the
ServletContextis bound to the lifespan of the WAC, not the test that uses the WAC. My first thoughts in implementating this web test feature was a test case that creates aServletContextin@BeforeClassand then symmetrically "destroys" it in@AfterClass. But the context caching feature introduces another lifecycle that is not bound to the test lifecycle; theServletContextis definitively part of this alternate lifecycle.Regarding web tests without WAC, a simple TestExecutionListener can do the job :
@Autowiredfields of type ServletRequest, ServletResponse, HttpSession, ServletContext, etc. (or subclasses).@AutowiredfieldsThis helps writing tests for a POJO web controller that does not need application context infrastructure, but just access to a request/response pair and maybe a user session. With such a listener, there's no need to write a
@Beforemethod that creates all these objects. But it's not linked to WAC and thus not linked to this JIRA issue. I can write such a listener by myself.Regarding security, I created the issue SEC-2015.
Regards,
Gaëtan
spring-projects-issues commentedon Jul 20, 2012
Sam Brannen commented
This issue depends on #10284 in order to support common context hierarchies in Spring MVC web applications.
spring-projects-issues commentedon Jul 20, 2012
Rossen Stoyanchev commented
The spring-test-mvc project (to be included in Spring 3.2) might fit this description. The "standalone" setup does not require an ApplicationContext and uses the mock request/response internally. See this example as well as many others in that package and sub-packages.
spring-projects-issues commentedon Oct 7, 2012
Sam Brannen commented
If you're following this issue, you may interested in knowing that support for
WebApplicationContexthierarchies in integration tests has been split out into a new issue: #14496Regards,
Sam
spring-projects-issues commentedon Oct 7, 2012
Sam Brannen commented
Pull request submitted: #160
spring-projects-issues commentedon Oct 7, 2012
Sam Brannen commented
This work has been addressed as discussed in the comments for GitHub commit 9937f840d5:
spring-projects-issues commentedon Oct 31, 2012
Sam Brannen commented
Note that
WebTestExecutionListenerhas been renamed toServletTestExecutionListener.