How can i inject servletcontext in spring
I need to write a junit test for a rather complex application which runs in a tomcat.
I wrote a class which builds up my spring context.
private static ApplicationContext springContext = null;
springContext = new ClassPathXmlApplicationContext( new String[] {"beans"....});
In the application there is a call:
public class myClass implements ServletContextAware {
.... final String folder = servletContext.getRealPath ("/example"); ... }
which breaks everything, because the ServletContext is null.
I have started to build a mock object:
static ServletConfig servletConfigMock = createMock(ServletConfig.class);
static ServletContext servletContextMock = createMock(ServletContext.class);
@BeforeClass public static void setUpBeforeClass() throws Exception {
expect(servletConfigMock.getServletContext()).andReturn(servletContextMock).anyTimes(); expect(servletContextMock.getRealPath("/example")).andReturn("...fulllpath").anyTimes();
replay(servletConfigMock);
replay(servletContextMock);
}
Is there a simple methode to inject the ServletContext or to start the tomcat with a deployment descriptor at the runtime of the junit test?
I am using: spring, maven, tomcat 6 and easymock for the mock objects.
What you actually want is to test the web-layer. There are a couple of ways to do it:
MockServletContext
provided by spring. This is the best way - check the linked documentation for how to do it. And whenever you want to inject something in a test, use ReflectionTestUtils
The complication comes from the fact that the web-layer is not quite suitable for unit-testing. It is more a subject of functional testing.
If there are methods that seem suitable for unit-testing, they perhaps belong to the service layer. And they should not have a dependency on the ServletContext
上一篇: 如何编写动态测试用例