泽西岛JUnit测试:未调用@WebListener ServletContextListener [英] Jersey JUnit Test: @WebListener ServletContextListener not invoked

查看:105
本文介绍了泽西岛JUnit测试:未调用@WebListener ServletContextListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在泽西岛创建了该测试(来自 docs ),效果很好,但有一个问题:@WebListener ServletContextListener没有被调用.

I created this test in Jersey (from the docs), which works fine, with one problem: the @WebListener ServletContextListener is not being invoked.

我需要测试的Resource类依赖于ServletContextListener在ServletContext上设置的属性.

The Resource classes that I need to test rely on an attribute set on the ServletContext by the ServletContextListener.

我可以确保它被调用,还是可以其他方式操纵ServletContext?

Can I make sure it is invoked, or can I manipulate the ServletContext in some other way?

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);
    }
}

我添加了这些依赖关系以使其正常工作:

I added these dependencies to make this work:

<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>

推荐答案

JerseyTest需要设置为在Servlet环境中运行,例如

The JerseyTest needs to be set up to run in a Servlet environment, as mentioned here. Here are the good parts:

@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();
}

请参阅

  • ServletDeploymentContext and
  • ServletDeployementContext.Builder (which is what is returned when you call forServlet on the ServletDeploymentContext).

这篇关于泽西岛JUnit测试:未调用@WebListener ServletContextListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆