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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Update User Details in API Test Client Using REST Assured [Video]
  • Create User API Test Client With REST Assured [Video]
  • Penetration Test Types for (REST) API Security Tests
  • What Is API-First?

Trending

  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • Why Database Migrations Take Months and How to Speed Them Up
  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.1K 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]
  • Penetration Test Types for (REST) API Security Tests
  • What Is API-First?

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!