Skip to main content

Posts

Showing posts from July, 2016

Setting up Spring application & webapp contexts correctly in Java integration tests

When integration testing Spring web applications you would often pull in the applicationContext.xml and the appropriate *-servlet.xml file using the @ContextConfiguration annotation within the junit test class. The problem is that this loads both sets of beans into the same context which is different from when tcServer loads the webapp for real. In a real server, the application context is loaded into the 'root' context and each servlet into it's own separate context which is dependent on the root (see my set of previous articles for more details). To properly set up the contexts in a test environment so that they are loaded and treated the same as in a running tcServer you need to tell the test that it's a webapp test using the @WebAppConfiguration annotation and then use the @ContextHierarchy annotation to set up the order in which to load the contexts: @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(