2

我想对WebApplicationContextUtils.getRequiredWebApplicationContext(context)在其init()方法中依赖于 Spring 的 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(...) 可以返回它。

4

1 回答 1

9

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

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

这是有效的,因为使用键(常量)WebApplicationContextUtils获取存储的对象。ServletContextorg.springframework.web.context.WebApplicationContext.ROOTWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE

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

于 2011-12-11T15:02:17.647 回答