我在Jersey(来自docs)创建了这个测试,它运行正常,但有一个问题:@WebListener ServletContextListener
没有被调用。
我需要测试的Resource类依赖于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>
答案 0 :(得分:4)
需要将JerseyTest
设置为在Servlet环境中运行,如mentioned here。以下是好的部分:
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
@Override
protected DeploymentContext configureDeployment() {
ResourceConfig config = new ResourceConfig(SessionResource.class);
return ServletDeploymentContext.forServlet(new ServletContainer(config))
.addListener(AppContextListener.class)
.build();
}
请参阅API
ServletDeploymentContext
和ServletDeployementContext.Builder
(当您在forServlet
上致电ServletDeploymentContext
时返回的内容。)