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 method 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:
MockServletContextprovided 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
ReflectionTestUtilsThe 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