Reputation: 5032
Due to custom framework dependencies, I cannot upgrade to Spring 3.2+. I'm stuck on 3.1.x. I am trying to obtain a WebApplicationContext in a Spring JUnit test like so:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring/context.xml")
public class WebIntegrationTest {
@Autowired
private WebApplicationContext ctx;
This, as expected, does not load a WebApplicationContext.
I realize that in Spring 3.2 or later I could just use @WebAppConfiguration
to tell Spring that I want a web context provided, but how can I achieve this with my dependency constraints?
Upvotes: 2
Views: 1391
Reputation: 18167
I too am stuck on 3.1, at least until I can get enough testing around this code to upgrade - but can't test enough until I can get a working WebApplicationContext...
It isn't too hard to construct the WebApplicationContext, only a whole morning of trial and error.
So, for a test like
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = MyLoader.class,
locations =
{
"file:WEB-INF/springcontexts/spring-security-common.xml",
"file:WEB-INF/springcontexts/webapp-common.xml"
})
public class LoginIntegrationTest {
you can define
public class MyLoader implements ContextLoader {
@Override
public String[] processLocations(Class<?> clazz, String... locations) {
return locations;
}
@Override
public ApplicationContext loadContext(String... locations) throws Exception {
XmlWebApplicationContext result = new XmlWebApplicationContext();
MockServletContext servletContext = new MockServletContext("target/webapp", new FileSystemResourceLoader());
result.setServletContext(servletContext);
result.setServletConfig(new MockServletConfig(servletContext));
result.setConfigLocations(locations);
result.refresh();
return result;
}
}
You'll need to change the paths to match your own, or pass them around somehow.
Upvotes: 2