Jersey JUnit Test: @WebListener ServletContextListener not invoked

吃可爱长大的小学妹 提交于 2019-12-07 14:39:38

问题


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

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

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>

回答1:


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

See the APIs for

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


来源:https://stackoverflow.com/questions/30896911/jersey-junit-test-weblistener-servletcontextlistener-not-invoked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!