Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3 - Testing a controller @Autowired Servlet Context

I have a controller with the following annotation

@Autowired
ServletContext servletContext;

which seems to work fine and to autowired the servlet context properly. However when I try to run the junit I get the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ControllerTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.servlet.ServletContext

The strange issue is that this only happened with ServletContext, I have other beans autowired on this particular controller and unit tests works fine for those.

Any advice would be very helpful.

like image 807
tsunade21 Avatar asked Mar 14 '11 15:03

tsunade21


2 Answers

As @bluefoot states, you should use MockServletContext. For this to work, instead of auto wiring the ServletContext, you can implement ServletContextAware. Spring will notice this when running in a web application context and inject the ServletContext and in the JUnit test you can call the setServletContext method to set the MockServletContext.

like image 113
krock Avatar answered Oct 17 '22 01:10

krock


Well, your're not supposed to have a real ServletContext inside a junit test ambient.

You should use MockServletContext.

like image 21
bluefoot Avatar answered Oct 17 '22 00:10

bluefoot