【问题标题】:Unit testing a Servlet that depends on Spring's WebApplicationContextUtils.getRequiredWebApplicationContext(context)对依赖于 Spring 的 WebApplicationContextUtils.getRequiredWebApplicationContext(context) 的 Servlet 进行单元测试
【发布时间】:2012-01-17 21:24:55
【问题描述】:

我想在 init() 方法中对依赖 Spring 的 WebApplicationContextUtils.getRequiredWebApplicationContext(context) 的 servlet 代码进行单元测试。

下面是部分代码:

@Override
public void init() throws ServletException {
super.init();
WebApplicationContext applicationContext =
    WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
this.injectedServiceBean = (SomeService) applicationContext.getBean("someBean");
}

将适当的 applicationContext.xml(测试版本)注入此文本的最佳方法是什么?

我知道 Spring 的 @ContextConfiguration,但我不确定将由该注释加载的 ${testClass}Test-context.xml 上下文注入 servlet 上下文的最佳方法,以便 getRequiredWebApplicationContext(... ) 可以退货。

【问题讨论】:

    标签: java spring unit-testing servlets applicationcontext


    【解决方案1】:

    您可以通过以下方式注入应用程序上下文:

    getServletContext().setAttribute(
      WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
      testApplicationContext
    );
    

    这是因为WebApplicationContextUtils 使用org.springframework.web.context.WebApplicationContext.ROOT 键(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 常量)获取存储在ServletContext 中的对象。

    这仅表明直接从应用程序上下文中获取 bean 是有问题的,因为这种方法不遵循 DI 规则。如果可以,请尝试重构此 servlet 以将其与 Spring 更好地集成(例如,使用 HttpRequestHandlerServlet see example)。

    【讨论】:

    • 你能添加一个例子,可能是一个完整的测试?
    • 我收到此错误java.lang.IllegalStateException: Context attribute is not of type WebApplicationContext: org.springframework.context.support.GenericApplicationContext
    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多