Reputation: 16651
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>
Upvotes: 4
Views: 3073
Reputation: 209052
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
andServletDeployementContext.Builder
(which is what is returned when you call forServlet
on the ServletDeploymentContext
).Upvotes: 6