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;
...
}
Best Answer
According to ptomli hint, defining
MockServletContext
bean do the trick.Another problem, which appeared was tilesConfigurer, that doesn't work:
Soultion: separate tiles config from applicationContext.xml and don't use tiles in jUnit tests.