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

  • 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]
  • Update User Details in API Test Client Using REST Assured [Video]

Trending

  • AI-Based Threat Detection in Cloud Security
  • How to Practice TDD With Kotlin
  • Docker Base Images Demystified: A Practical Guide
  • Docker Model Runner: Streamlining AI Deployment for Developers
  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 user avatar
Biplab Pal
·
Feb. 06, 18 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
57.6K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • 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]
  • Update User Details in API Test Client Using REST Assured [Video]

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!