我想在其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
,但我不确定注入由该注释加载到servlet上下文中的${testClass}Test-context.xml
上下文的最佳方法,以便getRequiredWebApplicationContext(…)可以返回它。
您可以通过以下方式注入应用程序上下文:
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
,参见示例)。
我必须使用这个静态WebApplicationContextUtils.getRequiredWebApplicationContext
实用程序方法对访问应用程序上下文的servlet过滤器进行单元测试。
之前来自@Tomasz Nurkiewicz的回答帮助我正确地模拟测试的上下文。由于答案不包含实际的代码,我想分享我的实现,以防将来对某人有用。
WebApplicationContext applicationContext = mock(WebApplicationContext.class);
HttpSession httpSession = mock(HttpSession.class);
ServletContext servletContext = mock(ServletContext.class);
when(httpSession.getServletContext()).thenReturn(servletContext);
when(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE))
.thenReturn(applicationContext);
when(httpServletRequest.getSession()).thenReturn(httpSession);
在过滤器类本身中,我使用实用程序方法检索上下文。
ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(
httpServletRequest.getSession().getServletContext());