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.
As @bluefoot states, you should use
MockServletContext. For this to work, instead of auto wiring the ServletContext, you can implementServletContextAware. 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.