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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Testing REST Controller Methods With JUnit 5 [Video]

Trending

  • Build a Voice Assistant With Gemini Live API
  • Should Developers Switch From SQLite to DuckDB?
  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • Adding Graph Retrieval to a RAG Pipeline With Python

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Automated Testing for REST APIs

Automated Testing for REST APIs

REST APIs and microservices are exposed to the web, so security is important. Learn about automating your testing for these crucial APIs and services.

By 
Biplab Pal
·
Feb. 06, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
58.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Integration testing is the phase of software testing in which individual software modules are combined and tested as a group instead of testing each class independently. This can be achieved easily by using JUnit for backend code and Selenium for UI. Both of these tests can be part of Build/CI system to view the report and fail/pass the build/CI system.

Since all of us are now writing or maintaining RESTful microservices and these services/APIs are exposed to the web and distributed over different networks, they are vulnerable to risks and security threats which affect the processes based on them. Hence, testing becomes necessary to ensure they perform correctly. To test these APIs, it's very important to automate REST API test cases instead of relying on manual testing. This tutorial focuses on the basic principles, mechanics, and few ways of testing a REST API. For simplicity, the GitHub REST API will be used here.

There are various technologies and tools available; a few of them are Apache HTTP client, rest-assured, soapUI, Postman, etc. Out of all these, I will be describing Apache HTTP client, rest-assured, and soapUI.

This kind of testing will usually run as a late step in a Continuous Integration process, consuming the REST API after it has already been deployed.

When testing a REST API, the tests should focus on:

  • HTTP response code

  • Response body - JSON, XML

  •  HTTP headers in the response

1. Writing Test Cases With Apache HTTP Client

HttpClient provides an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations.

  • HTTP response code

public void validStatusCode() throws  IOException {
     HttpUriRequest request = new HttpGet( "https://api.github.com/events" );
     HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request );     
     Assert.assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(HttpStatus.OK));
}
  • Response body & header

 public void responseBody() IOException {
    String jsonMimeType =  "application/json";
HttpUriRequest request = new HttpGet( "https://api.github.com/events" );
HttpResponse response = HttpClientBuilder.create().build().execute( request );
String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
    Event[] events = new ObjectMapper().readValue(response.getEntity().
                     getContent(), Event[].class);       
 Assert.assertEquals( jsonMimeType, mimeType );
   // more assert starments can be added here
 }
@JsonIgnoreProperties(ignoreUnknown = true)// this is added since new ObjectMapper().readValue(response.getEntity().getContent(), Event[].class);
//throw will exception if don't have all properties(part of the response) present in this class
class Event {
    private String type;
    private long id;
    private Repo repo;
    // setters and getters for all properties goes here
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Repo {
    private long id;
    private String name;
// setters and getters for all properties goes here

}


2. Writing Test Cases With rest-assured

REST-assured is a Java DSL (domain specific language) for simplifying testing of REST-based services built on top of HTTP Builder. It supports POST, GET, PUT, DELETE, OPTIONS, PATCH, and HEAD requests and can be used to validate and verify the response of these requests

  • HTTP response code, response body & header.

@Test
public void getStatusWithRestAssured() {
  Event[] events =  RestAssured.get("https://api.github.com/events").then()
               .statusCode(200).assertThat().contentType(ContentType.JSON)
               .body("", CoreMatchers.notNullValue())
               .extract().as(Event[].class);
  // more assert statement goes here.
}

With rest-assured, various test scenarios can be covered in a very simple way. More details about rest-assured are available here.

3. Writing Test Cases With SoapUI

SoapUI is an open source, cross-platform testing tool. It can automate functional, regression, compliance and load testing of both SOAP and REST web services. It comes with an easy-to-use graphical interface and supports industry-leading technologies and standards to mock and stimulate the behavior of web services.

Below are the steps needed to set it up and details about each step are available here.

  1. Creation of soapUI test project.
  2. Defining endpoints.
  3. Test case and test suite creation.
  4. Addition of test steps for endpoints.
  5. Generating the project descriptor.

Once we are done with the above steps, create a maven project with below plugin added in the pom. The below snippet assumes that the name of the project descriptor file is project.xml.

<plugin>
<groupId>com.smartbear.soapui</groupId>
    <artifactId>soapui-maven-plugin</artifactId>
    <version>5.2.1</version>
    <configuration>
    <projectFile>${basedir}/project.xml</projectFile>
</configuration>
    <executions>
    <execution>
<id>soapui-test</id>
         <phase>integration-test</phase>
         <goals>
            <goal>test</goal>
         </goals>
    </execution>
</executions>
</plugin>

 If it is not available under the default Maven repo, you would need to add the following repository:

<pluginRepositories>
<pluginRepository>
    <id>smartbear-sweden-plugin-repository</id>
    <url>http://www.soapui.org/repository/maven2</url>
  </pluginRepository>
</pluginRepositories>


Run the following Maven command to run all your tests:

mvn clean integration-test
mvn clean integration-test
REST Web Protocols

Opinions expressed by DZone contributors are their own.

Related

  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Testing REST Controller Methods With JUnit 5 [Video]

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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