Issue
I'd like to unit-test a servlet code that relies on Spring's WebApplicationContextUtils.getRequiredWebApplicationContext(context)
in its init()
method.
Here is part of the code:
@Override
public void init() throws ServletException {
super.init();
WebApplicationContext applicationContext =
WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
this.injectedServiceBean = (SomeService) applicationContext.getBean("someBean");
}
What would be the best way to inject a proper applicationContext.xml (test version) into this text?
I'm aware of Spring's @ContextConfiguration
, but it I'm not sure about the best approach to inject the ${testClass}Test-context.xml
context that is loaded by that annotation into the servlet context, so that the getRequiredWebApplicationContext(...) can return it.
Solution
You can inject application context in the following way:
getServletContext().setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
testApplicationContext
);
This works because WebApplicationContextUtils
fetches an object stored in ServletContext
with org.springframework.web.context.WebApplicationContext.ROOT
key (WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
constant).
This only shows that fetching beans directly from an application context is problematic since this approach does not follow DI rules. If you can, try refactoring this servlet to integrate it better with Spring (e.g. using HttpRequestHandlerServlet
see example).
Answered By - Tomasz Nurkiewicz
Answer Checked By - Robin (JavaFixing Admin)