单元测试Spring MVC web-app:无法自动装配字段:private javax.servlet.ServletContext

mar*_*osh 11 spring unit-testing spring-mvc

我想为我的网络应用程序进行测试,但上下文配置在自动装配时崩溃servletContext.错误如下.servletContext当我在tomcat/jetty上运行web-app时,自动装配工作正常.

java.lang.IllegalStateException:无法加载ApplicationContext ...由以下原因引起:org.springframework.beans.factory.BeanCreationException:创建名为'testController'的bean时出错:注入自动连接的依赖项失败; 嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private javax.servlet.ServletContext com.test.controllers.TestController.servletContext; 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为[javax.servlet.ServletContext]的匹配bean:期望至少有一个bean可以作为此依赖项的autowire候选者.依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class FirstTest {

    @Test
    public void doTest() throws Exception {
        // ...  
    }
}
Run Code Online (Sandbox Code Playgroud)

的TestController

@Controller
public class TestController {

    @Autowired
    private ServletContext servletContext;

    ... 
}
Run Code Online (Sandbox Code Playgroud)

mar*_*osh 25

根据ptomli提示,定义MockServletContextbean可以解决问题.

<bean class="org.springframework.mock.web.MockServletContext"/>
Run Code Online (Sandbox Code Playgroud)

出现的另一个问题是tilesConfigurer,它不起作用:

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
Run Code Online (Sandbox Code Playgroud)

Soultion:从applicationContext.xml中分离tiles配置,并且不在jUnit测试中使用tile.

<?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>
Run Code Online (Sandbox Code Playgroud)

  • 有用.另一种选择是使用@WebAppConfiguration来进行测试 (4认同)

gst*_*low 10

我已经@WebAppConfiguration在测试类下添加了,问题就消失了