【问题标题】:Unit testing Spring MVC web-app: Could not autowire field: private javax.servlet.ServletContext单元测试 Spring MVC web-app:无法自动装配字段:私有 javax.servlet.ServletContext
【发布时间】:2011-11-20 06:08:02
【问题描述】:

我想为我的网络应用程序进行测试,但上下文配置在自动装配 servletContext 时崩溃。下面的错误。当我在 tomcat/jetty 上运行 web-app 时,自动装配 servletContext 效果很好。

java.lang.IllegalStateException: 无法加载 ApplicationContext ... 引起:org.springframework.beans.factory.BeanCreationException: 创建名为“testController”的bean时出错:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 javax.servlet.ServletContext com.test.controllers.TestController.servletContext;嵌套异常 是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 找到类型为 [javax.servlet.ServletContext] 的匹配 bean 依赖项:预计至少有 1 个符合自动装配条件的 bean 这种依赖的候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

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

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

测试控制器

@Controller
public class TestController {

    @Autowired
    private ServletContext servletContext;

    ... 
}

【问题讨论】:

  • 谢谢。如何将MockServletContext@ContextConfiguration 一起使用?
  • 只需在applicationContext.xml 文件中包含MockServletContext 定义

标签: unit-testing spring spring-mvc


【解决方案1】:

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

Soultion:将磁贴配置与 applicationContext.xml 分开,不要在 jUnit 测试中使用磁贴。

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

【讨论】:

  • 它有效。另一种选择是使用 @WebAppConfiguration 注释测试
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 2023-03-13
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2014-02-26
    • 2015-09-11
    • 2018-09-17
    相关资源
    最近更新 更多