Testing a JAX-RS Web Service? Testing a JAX-RS Web Service? java java

Testing a JAX-RS Web Service?


Jersey comes with a great RESTful client API that makes writing unit tests really easy. See the unit tests in the examples that ship with Jersey. We use this approach to test the REST support in Apache Camel, if you are interested the test cases are here


You can try out REST Assured which makes it very simple to test REST services and validating the response in Java (using JUnit or TestNG).


As James said; There is built-in test framework for Jersey. A simple hello world example can be like this:

pom.xml for maven integration. When you run mvn test. Frameworks start a grizzly container. You can use jetty or tomcat via changing dependencies.

...<dependencies>  <dependency>    <groupId>org.glassfish.jersey.containers</groupId>    <artifactId>jersey-container-servlet</artifactId>    <version>2.16</version>  </dependency>  <dependency>    <groupId>org.glassfish.jersey.test-framework</groupId>    <artifactId>jersey-test-framework-core</artifactId>    <version>2.16</version>    <scope>test</scope>  </dependency>  <dependency>    <groupId>org.glassfish.jersey.test-framework.providers</groupId>    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>    <version>2.16</version>    <scope>test</scope>  </dependency></dependencies>...

ExampleApp.java

import javax.ws.rs.ApplicationPath;import javax.ws.rs.core.Application;@ApplicationPath("/")public class ExampleApp extends Application {}

HelloWorld.java

import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;@Path("/")public final class HelloWorld {    @GET    @Path("/hello")    @Produces(MediaType.TEXT_PLAIN)    public String sayHelloWorld() {        return "Hello World!";    }}

HelloWorldTest.java

import org.glassfish.jersey.server.ResourceConfig;import org.glassfish.jersey.test.JerseyTest;import org.junit.Test;import javax.ws.rs.core.Application;import static org.junit.Assert.assertEquals;public class HelloWorldTest extends JerseyTest {    @Test    public void testSayHello() {        final String hello = target("hello").request().get(String.class);        assertEquals("Hello World!", hello);    }    @Override    protected Application configure() {        return new ResourceConfig(HelloWorld.class);    }}

You can check this sample application.