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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Mark Paluch user avatar by
Mark Paluch
·
Mar. 13, 15 · Tutorial
Like (6)
Save
Tweet
Share
307.57K 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.

Popular on DZone

  • Demystifying the Infrastructure as Code Landscape
  • What “The Rings of Power” Taught Me About a Career in Tech
  • The Power of Docker Images: A Comprehensive Guide to Building From Scratch
  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: