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 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.
Well, your're not supposed to have a real ServletContext
inside a junit test ambient.
You should use MockServletContext.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With