How to inject ServletContext for JUnit tests with Spring?

Juri Glass picture Juri Glass · Apr 20, 2010 · Viewed 24.6k times · Source

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.

Answer

Chris J picture Chris J · Apr 20, 2010

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.