gpt4 book ai didi

java - 对依赖于 Spring 的 WebApplicationContextUtils.getRequiredWebApplicationContext(context) 的 Servlet 进行单元测试

转载 作者:行者123 更新时间:2023-12-02 19:38:21 24 4
gpt4 key购买 nike

我想对依赖 Spring 的 init() 方法中的 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(测试版本)注入(inject)此文本的最佳方法是什么?

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

最佳答案

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

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

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

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

关于java - 对依赖于 Spring 的 WebApplicationContextUtils.getRequiredWebApplicationContext(context) 的 Servlet 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8464919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com