【发布时间】:2014-04-10 10:59:23
【问题描述】:
我需要测试一个 servlet,它现在工作正常。
servlet 需要使用 Spring 服务,因此对其进行了修改:
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(
this, config.getServletContext()); // ImageServlet.java line 49
迁移到 Spring 4 后,测试中断,目前抛出此异常:
java.lang.IllegalStateException:
No WebApplicationContext found: no ContextLoaderListener registered?
at org.springframework.web.context.support.WebApplicationContextUtils.
getRequiredWebApplicationContext(WebApplicationContextUtils.java:84)
at org.springframework.web.context.support.SpringBeanAutowiringSupport.
processInjectionBasedOnServletContext(SpringBeanAutowiringSupport.java:107)
at package.ImageServlet.init(ImageServlet.java:49)
at in.nasv.utils.ImageServletTest.accessingImageViaHttp(ImageServletTest.java:45)
这是 ImageServletTest 的部分代码:
// prepare servlet instance
MockServletConfig config = new MockServletConfig(
new MockServletContextPatched());
ImageServlet servlet = new ImageServlet();
servlet.init( config ); // ImageServletTest, line 45
而这个打补丁的类(现在实际上并没有打补丁):
public class MockServletContextPatched extends MockServletContext{ }
我应该怎么做才能避免这种“IllegalStateException:未找到 WebApplicationContext:未注册 ContextLoaderListener?” ?
【问题讨论】:
-
你真的需要调用
init()方法来测试你的Servlet吗?如果没有,我建议您只实例化您的 Servlet 并手动注入其依赖项,而不是在测试中依赖SpringBeanAutowiringSupport。 -
很好的方法,但不适用于我的情况。 Spring MockServletContext 的功能非常有限(没有 setter 和 getter 只返回固定值,虚拟 Spring!)所以我需要扩展它。我只能通过 init() 应用它
-
Spring 的
MockServletContext确实有二传手。您认为 Spring 的MockServletContext有哪些限制?您的自定义MockServletContextPatched有什么特别之处? -
我需要 MimeType 的 setter,但只有 getter 存在。我的 MockServletContextPatched 扩展了这个。是的,MockServletContext 有 3 个额外的 setter,但许多其他的没有 - 限制 Spring 模拟类的功能。
-
MockServletContext中没有用于 MIME 类型的 setter 方法,因为 Spring 使用 Java 激活框架来解析传递给getMimeType(String)的文件名的 MIME 类型。如果您需要一种方法来设置 Java 激活框架不支持的自定义 MIME 类型,请针对“Spring Framework”项目和“测试”组件创建一个新的 JIRA 问题以请求该功能。
标签: java spring servlets spring-test