I would like to make tests for my web-app, but context configuration crashes on autowiring servletContext
. Error below. Autowiring servletContext
works good when i run web-app on tomcat/jetty.
java.lang.IllegalStateException: Failed to load ApplicationContext ... Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.servlet.ServletContext com.test.controllers.TestController.servletContext; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class FirstTest {
@Test
public void doTest() throws Exception {
// ...
}
}
TestController
@Controller
public class TestController {
@Autowired
private ServletContext servletContext;
...
}
According to ptomli hint, defining MockServletContext
bean do the trick.
<bean class="org.springframework.mock.web.MockServletContext"/>
Another problem, which appeared was tilesConfigurer, that doesn't work:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
Soultion: separate tiles config from applicationContext.xml and don't use tiles in jUnit tests.
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:tilesConfig.xml
</param-value>
</context-param>
</web-app>
I have added @WebAppConfiguration
under the test class and problem disappeared
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