DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Update User Details in API Test Client Using REST Assured [Video]
  • Create User API Test Client With REST Assured [Video]
  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • What Is API-First?

Trending

  • AI in Software Development: A Mirror, Not a Magic Wand
  • Reactive Kafka With Spring Boot
  • Product-Led Software Delivery: Intelligent Platforms for DevOps at Scale
  • End-to-End Event Streaming With Kafka, Spring Boot and AWS SQS/SNS (Production-Ready Code Guide)
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How to Test a REST API With JUnit

How to Test a REST API With JUnit

RESTEasy (and Jersey as well) contain a minimal web server within their libraries which enables their users to start up a tiny web server.

By 
Mark Paluch user avatar
Mark Paluch
·
Mar. 13, 15 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
311.5K Views

Join the DZone community and get the full member experience.

Join For Free

Do you want to test your REST API as soon as possible and without any hassle? The earliest point in the code where tests can occur is within the commit stage, where you can run unit tests. I want to present you an approach how to test REST API as soon as possible in an easy way. The example code is based on JUnit and RESTEasy. It does not require any external database or heavyweight application servers which means you can run it isolated and out of the box.

RESTEasy (and Jersey as well) contains a minimal web server within their libraries which enables their users to start up a tiny web server, either for production use or to run tests.

TJWSEmbeddedJaxrsServer server = new TJWSEmbeddedJaxrsServer();
server.setPort("12345");

server.getDeployment().getResources().add(myResourceInstance);

// alternative
server.getDeployment().getProviderClasses().add("com.my.my.resource.class.name");
server.start();
The server will mount your resources without any context prefix. You are ready to start your tests.


new ResteasyClientBuilder().build().target("http://localhost:12345/myresource").request().get()


That's it. Some test cases are that simple. Other test cases require more features such as dynamic ports (e. g. when multiple builds run on the same machine), a security domain for authentication or a set of provider classes you need in order to marshal/unmarshal/convert exceptions. These requirements can lead to a lot of boilerplate in each of your tests. I want to present a more generic and reusable approach of testing REST APIs with JUnit and RESTEasy 3.0 :

public class InMemoryRestTest {
@Path("myresource")
    public static class MyResource {

        @POST
        @Consumes(MediaType.TEXT_PLAIN)
        @Produces(MediaType.APPLICATION_XML)
        public MyModel createMyModel(int number) {

            return new MyModel(number);
        }

    }

    public static MyResource sut = new MyResource();
    public static InMemoryRestServer server;

    @BeforeClass
    public static void beforeClass() throws Exception {
        server = InMemoryRestServer.create(sut);
    }

    @AfterClass
    public static void afterClass() throws Exception {
        server.close();
    }

    @Test
    public void postSimpleBody() throws Exception {

        Response response = server.newRequest("/myresource").request().buildPost(Entity.text("42")).invoke();
        assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

        MyModel myModel = response.readEntity(MyModel.class);
        assertEquals(42, myModel.getResult());
    }
}

This test has everything built it to provide a REST API and consume it in one unit. MyResource is the REST service providing functionality, and the RESTEasy client utilizes the API.

All bootstrapping and REST server setup is encapsulated by InMemoryRestServer that also provides a handy entry point to testing. You no longer need to deal with port numbers in your test code. You can find the full code here.

Sometimes your code depends on further services or functionality that are located within other classes or behind interfaces. Usually, you would use a mock to simulate that behavior. So let's try that.

@RunWith(MockitoJUnitRunner.class)
public class InMemoryRestWithMockitoTest {

    public static interface BackendService {

        MyModel getMyModel(int number);
    }

    @Path("myresource")
    public static class MyResource {

        private BackendService backendService;

        @POST
        @Consumes(MediaType.TEXT_PLAIN)
        @Produces(MediaType.APPLICATION_XML)
        public MyModel createMyModel(int number) {

            return backendService.getMyModel(number);
        }

    }

    @InjectMocks
    public static MyResource sut = new MyResource();
    public static InMemoryRestServer server;

    @Mock
    private BackendService backendServiceMock;

    @BeforeClass
    public static void beforeClass() throws Exception {
        server = InMemoryRestServer.create(sut);
    }

    @AfterClass
    public static void afterClass() throws Exception {
        server.close();
    }

    @Test
    public void postWithoutMocking() throws Exception {

        Response response = server.newRequest("/myresource").request().buildPost(Entity.text("42")).invoke();
        assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
    }

    @Test
    public void postWithMocking() throws Exception {

        when(backendServiceMock.getMyModel(42)).thenReturn(new MyModel(42));

        Response response = server.newRequest("/myresource").request().buildPost(Entity.text("42")).invoke();
        assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

        MyModel myModel = response.readEntity(MyModel.class);
        assertEquals(42, myModel.getResult());
    } 
  }

This code is not much more complicated than without mocking. You can use the mocking framework of your choice (here I used Mockito), inject the mocks into your REST API service and run your tests. You can find all code on GitHub.

REST Web Protocols API Testing JUnit

Published at DZone with permission of Mark Paluch. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Update User Details in API Test Client Using REST Assured [Video]
  • Create User API Test Client With REST Assured [Video]
  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • What Is API-First?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook