Seb*_*ian 2 java spring unit-testing servlets applicationcontext
我想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");
}
Run Code Online (Sandbox Code Playgroud)
将适当的applicationContext.xml(测试版本)注入此文本的最佳方法是什么?
我知道Spring的@ContextConfiguration,但是我不确定将${testClass}Test-context.xml注释加载到servlet上下文中的上下文注入的最佳方法,以便getRequiredWebApplicationContext(...)可以返回它.
您可以通过以下方式注入应用程序上下文:
getServletContext().setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
testApplicationContext
);
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为使用key(常量)WebApplicationContextUtils获取存储的对象.ServletContextorg.springframework.web.context.WebApplicationContext.ROOTWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
这仅表明直接从应用程序上下文中提取bean是有问题的,因为这种方法不遵循DI规则.如果可以的话,尝试重构这个servlet以便更好地与Spring集成(例如使用参见示例).HttpRequestHandlerServlet
| 归档时间: |
|
| 查看次数: |
2495 次 |
| 最近记录: |