20

I want to unit test a RESTful interface written with Apache CXF.

I use a ServletContext to load some resources, so I have:

@Context
private ServletContext servletContext;

If I deploy this on Glassfish, the ServletContext is injected and it works like expected. But I don't know how to inject the ServletContext in my service class, so that I can test it with a JUnit test.

I use Spring 3.0, JUnit 4, CXF 2.2.3 and Maven.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Juri Glass
  • 88,173
  • 8
  • 33
  • 46
  • See http://stackoverflow.com/questions/2665773/spring-i-wish-to-create-a-junit-test-for-a-web-application-webapplicationconte – lexicore Apr 20 '10 at 12:31

3 Answers3

22

In your unit test, you are probably going to want to create an instance of a MockServletContext.

You can then pass this instance to your service object through a setter method.

Gray
  • 115,027
  • 24
  • 293
  • 354
Chris J
  • 9,164
  • 7
  • 40
  • 39
18

As of Spring 4, @WebAppConfiguration annotation on unit test class should be sufficient, see Spring reference documentation

@ContextConfiguration
@WebAppConfiguration
public class WebAppTest {
    @Test
    public void testMe() {}
}
anre
  • 3,617
  • 26
  • 33
1

Probably you want to read resources with servletContext.getResourceAsStream or something like that, for this I've used Mockito like this:

 @BeforeClass
void setupContext() {

    ctx = mock(ServletContext.class);
    when(ctx.getResourceAsStream(anyString())).thenAnswer(new Answer<InputStream>() {
        String path = MyTestClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()
                + "../../src/main/webapp";

        @Override
        public InputStream answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            String relativePath = (String) args[0];
            InputStream is = new FileInputStream(path + relativePath);
            return is;
        }
    });

}