spring-mvc - 为内部依赖于 ContextLoader.getCurrentWebApplicationContext() 的 Spring MVC 应用程序编写 Junit 测试

标签 spring-mvc

我正在尝试为我们的 spring mvc 应用程序中的 Controller 编写集成测试。 Controller 调用一个服务类,该服务类又调用一个 dao 从存储库中读取/写入数据。 DAO 需要查找一些配置。配置 bean 定义在 WEB-INF/applicationContext.xml 中。

我正在使用这样的东西:

配置 config =(Configuration)ContextLoader.getCurrentWebApplicationContext().getBean("config");
私有(private)字符串命名空间 = config.getProperty("someproperty");

属性存储在 zookeeper 中,所以我没有使用 spring 的属性管理工件。

问题是在运行 JUnit 测试时 ContextLoader.getCurrentWebApplicationContext() 总是返回 null。

到目前为止,我已经研究了以下方法:
1. Ted Young的做法(随便google搜索spring mvc集成测试ted young)
2. https://github.com/SpringSource/spring-test-mvc
3.这个网站..问题/8464919/unit-testing-a-servlet-that-depends-on-springs-webapplicationcontextutils-getre
4. 使用 Selenium/JWebunit
5. http://confluence.highsource.org/display/Hifaces20/Hifaces20+Testing+package+-+testing%2C+tracing+and+debugging+web+applications+with+Jetty

1 没有解决这个问题。 WebApplicationContext 保持为空
2 声明在 spring 3.2 中将提供对 WebApplicationContext 的支持
3. 我不明白这个。我从哪里获得 testApplicationContext 和 getServletContext()?
4. 我不想走这条路,因为这完全是黑盒测试。
5. 我目前正在看 5. 但这需要启动一个 servlet 容器。没有其他选择吗?

我将不胜感激您能提供的任何帮助。

谢谢
PixalSoft

@Ted Young SO 不允许我完成我所说的话。使用 loader=MockWebApplicationContextLoader,它不应该可以作为默认上下文加载器使用,就像 Spring ContextLoader 在 webapp 由 servletcontainer 初始化时的行为一样吗?有吗?我需要做一些特别的事情来处理 MockWebApplicationContextLoader?注入(inject)配置对象适用于单例对象。但不可能都是单例的。在每个构造函数中传递一个配置对象听起来太乏味了。现在,我创建了一个具有静态配置对象的类,通过 setter 方法 Autowiring 。我会看看 ApplicationContextAware.Many thx

最佳答案

您必须手动将 Web 应用程序上下文添加到 ContextLoaderListener。
这将起作用。

@ContextConfiguration(locations = "classpath:module-test-beans.xml")
@WebAppConfiguration
public class SampleTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private WebApplicationContext wac;

    @BeforeClass
    public void setUp() throws ServletException {
        MockServletContext sc = new MockServletContext("");
        ServletContextListener listener = new ContextLoaderListener(wac);
        ServletContextEvent event = new ServletContextEvent(sc);
        listener.contextInitialized(event);
    }

    @Test
    public void testMe() {
        Assert.assertFalse(ContextLoader.getCurrentWebApplicationContext() == null);
    }
}

关于spring-mvc - 为内部依赖于 ContextLoader.getCurrentWebApplicationContext() 的 Spring MVC 应用程序编写 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10441622/

相关文章:

java - 在将 String 转换为一组对象的情况下,最好的 Spring 转换器策略是什么?

java - 书店应用的推荐系统

java - PayPal - Spring - 无效的 HTTP 方法 : PATCH

java - 不使用中间文件直接从SFTP下载文件到HTTP响应

java - 未经授权的错误 : Full authentication is required to access this resource with spring. 安全 v.6

java - Spring MVC 不会加载静态内容

java - NoClassDefFoundError : org/codehaus/jackson/Versioned using Jackson JSON parser

spring - 他们是使用 spring mvc 生成站点地图和机器人 txt 的现有工具吗

java - 从数据库或属性中获取 Spring Security 拦截 url

java - Maven 无法从 .m2/repository 找到 jar