Spring – Unit testing Spring MVC web-app: Could not autowire field: private javax.servlet.ServletContext

springspring-mvcunit testing

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.

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