Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey JUnit Test: @WebListener ServletContextListener not invoked

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>
like image 557
wvdz Avatar asked Oct 25 '25 05:10

wvdz


1 Answers

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).
like image 167
Paul Samsotha Avatar answered Oct 26 '25 18:10

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!