我想对我的Web应用程序进行测试,但是上下文配置在 Autowiring servletContext时崩溃。错误如下。当我在tomcat/jetty上运行web-app时, Autowiring servletContext效果很好。


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

    @Test
    public void doTest() throws Exception {
        // ...
    }
}

测试 Controller
@Controller
public class TestController {

    @Autowired
    private ServletContext servletContext;

    ...
}

最佳答案

根据ptomli提示,定义MockServletContext bean可以解决问题。

<bean class="org.springframework.mock.web.MockServletContext"/>

出现的另一个问题是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

解决方法:将tile配置与applicationContext.xml分开,并且不要在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>

关于unit-testing - 单元测试Spring MVC Web应用: Could not autowire field: private javax. servlet.ServletContext,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7471544/

10-12 00:36