views:

590

answers:

1

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.

+1  A: 

What you actually want is to test the web-layer. There are a couple of ways 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

Bozho
The mail goal is to save time: after each change, I would have to run maven and then start tomcat. It would have been nice if I could use the junit test to check - in my case a webservice, which has many dependencies - the functionality of the methode... basicly I want to wait less for each functiontest. I will look into ReflectionTestUtils. It seems promising. Thx for the hint.
M.R.