11
votes

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;

    ... 
}
2
See this related answer stackoverflow.com/questions/2674697/…ptomli
Thanks. How to use MockServletContext with @ContextConfiguration ?marioosh
Just include a <bean/> definition for the MockServletContext in your applicationContext.xml fileptomli

2 Answers

25
votes

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>
11
votes

I have added @WebAppConfiguration under the test class and problem disappeared