I've got a Jersey 3 Web application (running on Tomcat10, JDK15 with JUnit5) in which I would like to Unit test my Endpoints.
Although, I have troubles setting these up. What I understand is, that I need to use a GrizzlyWebTestContainer in order to get the correct environment setup. Also, I figure I need somehow to pass my web.xml to the ServletcContainer. But how would I do this?
When I run the test, I get:
java.lang.NullPointerException: Cannot invoke "org.glassfish.jersey.test.spi.TestContainer.getBaseUri()" because the return value of "org.glassfish.jersey.test.JerseyTest.getTestContainer()" is null
So I need to configure somewhere a baseUri as well - but where? Unfortunately, I've found only examples and documentations with GrizzlyTestContainerFactory instead of GrizzlyWebTestC... Could someone explain me what I did miss?
Any input is much appreciated!
This is my Unit test:
public class SimpleTest extends JerseyTest {
@Override
public TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
@Override
public DeploymentContext configureDeployment() {
return ServletDeploymentContext
.forServlet(new ServletContainer()) //how to pass web.xml here?
.build();
}
@Override
protected Application configure() {
return new ResourceConfig(DatasetController.class);
}
@Test
public void test() {
Response response = target("/data/180").request().get(); //--> NPE is thrown here
assertEquals(200, response.getStatus());
}
}
This my Endpoint, I would like to test:
@Path("/data")
public class DataController {
@Context ServletContext context;
private DataSource ds;
@PostConstruct
public void init() { ds = (DataSource) context.getAttribute(DATASOURCE_CONTEXT_NAME); }
@GET
@Path("/{dataId}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({"1","2"})
public Response getDataById(@PathParam("id") Long id) throws SQLException {
logger.debug("Fetching dataset with id " + id);
DSLContext create = DSL.using(ds.getConnection());
//some JOOQ code
return Response.ok(dto).build();
}
}
This is the most important part in my pom.xml
<dependencies>
<!-- Testing -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>