【发布时间】:2015-09-03 00:04:14
【问题描述】:
我在 Jersey 中创建了这个测试(来自 docs),它运行良好,但有一个问题:@WebListener ServletContextListener 没有被调用。
我需要测试的资源类依赖于 ServletContextListener 在 ServletContext 上设置的属性。
我可以确保它被调用,或者我可以以其他方式操作 ServletContext 吗?
public class SimpleTest extends JerseyTest {
@WebListener
public static class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("Context initialized");
}
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("Context destroyed");
}
}
@Path("hello")
public static class HelloResource {
@GET
public String getHello() {
return "Hello World!";
}
}
@Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
@Test
public void test() {
final String hello = target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
}
}
我添加了这些依赖项来完成这项工作:
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>2.18</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.18</version>
</dependency>
【问题讨论】:
-
ServletContextListener- 不是 JAX-RS 规范的一部分,所以我不认为 Jersey 会处理它,尤其是JerseyTest。 -
@DenysDenysiuk 是的,它是 servlet-api。但是我该如何解决这个问题呢?我正在测试的所有资源类都使用 ServletContext 来获取在我的 ServletContextListener 中设置的属性。操纵 ServletContext 的另一种方法也可以解决我的问题。
-
如果你只需要事件,你可以尝试使用jersey listeners而不是
ServletContextListener
标签: java rest junit jersey jax-rs