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

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

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

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

  • Event Storming Workshops: A Closer Look at Different Approaches
  • Microservices for Machine Learning
  • Stabilizing ETL Pipelines With Airflow, Presto, and Metadata Contracts
  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  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

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
  • [email protected]

Let's be friends: