📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
You can really easily test your services against a set of preconfigured containers or even an external container. In this guide, we’ll focus on a preconfigured container, namely jetty.
This guide covers,
- Jersey Test Framework Overview
- Jersey Test Framework Basics
- Supported Containers
- Running TestNG Tests
- Easy steps to write test using Jersey Test Framework
1. Jersey Test Framework Overview
- pre-configured client to access deployed application
- support for multiple containers - grizzly, in-memory, jdk, simple, jetty
- able to run against any external container
- automated configurable traffic logging
2. Jersey Test Framework Basics
@Path("/users")
public class UserResource {
private UserService userService = new UserService();
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> fetchAll() {
return userService.fetchAll();
}
@GET
@Path("user/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getById(@PathParam("id") int id) {
return Response.ok().entity(new User(100, "me", "me@gmail.com")).build();
}
}
public class UserResourceTest extends JerseyTest {
@Override
public Application configure() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
return new ResourceConfig(UserResource.class);
}
@Test
public void tesFetchAll() {
Response response = target("/users").request().get();
assertEquals("should return status 200", 200, response.getStatus());
assertNotNull("Should return user list", response.getEntity().toString());
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
}
@Test
public void testGetById() {
Response output = target("/users/user/100").request().get();
assertEquals("Should return status 200", 200, output.getStatus());
assertNotNull("Should return user object as json", output.getEntity());
System.out.println(output.getStatus());
System.out.println(output.readEntity(String.class));
}
}
3. Supported Containers
- Jersey provides 2 different test container factories based on Grizzly. The GrizzlyTestContainerFactory creates a container that can run as a light-weight, plain HTTP container. Almost all Jersey tests are using Grizzly HTTP test container factory. The second factory is GrizzlyWebTestContainerFactory that is Servlet-based and supports Servlet deployment context for tested applications. This factory can be useful when testing more complex Servlet-based application deployments.
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.27</version>
</dependency>
- The in-memory container is not a real container. It starts Jersey application and directly calls internal APIs to handle request created by client provided by test framework. There is no network communication involved. This container does not support servlet and other container dependent features, but it is a perfect choice for simple unit tests.
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-inmemory</artifactId>
<version>2.27</version>
</dependency>
- HttpServer from Oracle JDK is another supported test container.
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jdk-http</artifactId>
<version>2.27</version>
</dependency>
- Simple container (org.simpleframework.http) is another light-weight HTTP container that integrates with Jersey and is supported by Jersey Test Framework.
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-simple</artifactId>
<version>2.27</version>
</dependency>
- Jetty container (org.eclipse.jetty) is another high-performance, light-weight HTTP server that integrates with Jersey and is supported by Jersey Test Framework.
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jetty</artifactId>
<version>2.27</version>
</dependency>
4. Running TestNG Tests
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>...</version>
</dependency>
@BeforeClass
, teardown method with @AfterClass
.public class ContainerPerClassTest extends JerseyTestNg.ContainerPerClassTest {
@Path("/")
@Singleton
@Produces("text/plain")
public static class Resource {
private int i = 1;
@GET
public int get() {
return i++;
}
}
@Override
protected Application configure() {
return new ResourceConfig(Resource.class);
}
@Test(priority = 1)
public void first() throws Exception {
test(1);
}
@Test(priority = 2)
public void second() throws Exception {
test(2);
}
private void test(final Integer expected) {
final Response response = target().request().get();
assertEquals(response.getStatus(), 200);
assertEquals(response.readEntity(Integer.class), expected);
}
}
@BeforeMethod
, teardown method with @AfterMethod
.public class ContainerPerMethodTest extends JerseyTestNg.ContainerPerMethodTest {
@Path("/")
@Singleton
@Produces("text/plain")
public static class Resource {
private int i = 1;
@GET
public int get() {
return i++;
}
}
@Override
protected Application configure() {
return new ResourceConfig(Resource.class);
}
@Test
public void first() throws Exception {
test(1);
}
@Test
public void second() throws Exception {
test(1);
}
private void test(final Integer expected) {
final Response response = target().request().get();
assertEquals(response.getStatus(), 200);
assertEquals(response.readEntity(Integer.class), expected);
}
}
5. Steps to writing test using Jersey Test Framework
<!-- testing -->
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jetty</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
public class UserResourceTest extends JerseyTest {
}
public class UserResourceTest extends JerseyTest {
@Override
public Application configure() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
return new ResourceConfig(UserResource.class);
}
}
@Test
public void tesFetchAll() {
Response response = target("/users").request().get();
assertEquals("should return status 200", 200, response.getStatus());
assertNotNull("Should return user list", response.getEntity().toString());
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
}
@Test
public void testGetById() {
Response output = target("/users/user/100").request().get();
assertEquals("Should return status 200", 200, output.getStatus());
assertNotNull("Should return user object as json", output.getEntity());
System.out.println(output.getStatus());
System.out.println(output.readEntity(String.class));
}
- Using maven through the command line
mvn test -Dtest=classname
- From eclipse, right click and run as JUnit Test
Jun 14, 2018 11:20:02 AM org.glassfish.jersey.test.jetty.JettyTestContainerFactory$JettyTestContainer <init>
INFO: Creating JettyTestContainer configured at the base URI http://localhost:9998/
log4j:WARN No appenders could be found for logger (org.eclipse.jetty.util.log).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
200
[{"email":"demo@gmail.com","id":100,"name":"A"},{"email":"demo1@gmail.com","id":101,"name":"B"},{"email":"demo2@gmail.com","id":102,"name":"C"}]
Jun 14, 2018 11:20:04 AM org.glassfish.jersey.test.jetty.JettyTestContainerFactory$JettyTestContainer <init>
INFO: Creating JettyTestContainer configured at the base URI http://localhost:9998/
200
{"email":"me@gmail.com","id":100,"name":"me"}
Comments
Post a Comment
Leave Comment