REST Assured for Automating RESTful APIs
In microservices architecture, API testing becomes increasingly crucial. As a result, thorough testing of these APIs has become increasingly important. APIs are tested at a faster pace, resulting in quicker feedback retrieval. This will increase the productivity. API testing is performed before GUI (Graphical User Interface) testing, so it is simple to resolve minor issues while improving essential functionality.
How does Rest Assured help us?
REST Assured is a Java package that includes a domain-specific language (DSL) for developing effective and maintainable tests for RESTful APIs. RestAssured Framework, which offers developers a full lifecycle framework for Java projects, is built with Java and Maven, an automation tool based on POM (Project Object Model).
In this blog, we'll discuss REST Assured's installation, as well as how to create and execute tests.
API Testing with RestAssured Framework
During the development of an application, the RestAssured Framework assists in assessing and identifying errors. It is necessary to have knowledge of an IDE (IntelliJ or Eclipse), Maven, and frameworks such as TestNG, or JUnit in order to use RestAssured Framework for API Automation Testing. Rest APIs are tested by Manual Testing and Automation Testing. The most common way to test REST APIs is with automation, as it helps interpret results more effectively.
Rest API uses five HTTP methods for requesting commands as listed below:
- GET: Retrieves information from a specific URL.
- PUT: Updates previous resources or creates new information at the specified URL.
- PATCH: Partial updates.
- POST: Develops a new entity and is also used to send information to the server for uploading files or information.
- DELETE: Deletes the present representation at a particular URL.
API RestAssured Features
Code Reusability: Since it is a Java client, it can be done as REST-assured in terms of code reuse.
Customized Reports: It is a lightweight, multilingual test reporting tool that can be customized to specific needs. Graphical reports can be generated.
Designing a Data-Driven framework: With REST-assured automation, data files are not a limitation for the automation runner.
CI/CD integration: We can integrate into Jenkins tool.
Maintenance: Rest-assured provides us with DSL (Domain Specific Language). As a result, we can perform behaviour-driven tests.
Therefore, we can conclude that REST-assured is better than other tools for automating these RESTful web services, as it requires less maintenance and more efficiency.
Configuration Setup:
We used Maven as a build tool, so this article will concentrate solely on it. Before we begin, we must have the REST Assured dependency.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.3.3</version>
<scope>test</scope>
</dependency>
You can find the most recent versions of this dependency at https://mvnrepository.com/artifact/io.rest-assured/rest-assured . Other build tools' dependencies, such as sbt and Gradle, can also be found here.
With REST Assured, you can easily connect with other testing frameworks including TestNG, JUnit, etc. As you can see, we use TestNg in this blog. TestNg allows us to mark our test methods, add their description and priority, and tag them.
Now, we are ready to move to our test script:
We used Ergast Motor API as a sample reference implementation for this blog, which is publicly available. The API contains F1 motor racing data, such as drivers, circuits, and so on. It is available here. http://ergast.com/mrd
URL: http://ergast.com/mrd/.
All API queries require a GET request using a URL of the form:
http[s]://ergast.com/api/<series>/<season>/<round>/...
where:
<series> should be set to "f1"
<season> is a 4 digit integer
<round> is a 1 or 2 digit integer
For queries concerning a whole season, or final standings, the round element.
For example:
http://ergast.com/api/f1/2008/2
We have written a sample test script that provides us with a list of racetracks in JSON format
@Test(enabled = true)
public void circuitCount() {
given().
when().
get("http://ergast.com/api/f1/2017/circuits.json").
then().
assertThat().
body("MRData.CircuitTable.Circuits.circuitId",hasSize(20)); }
given() — We provide all the input details here i.e. Base URI, Headers, Path Parameter, Query Parameter, and Request Body/Payload.
when() — We specify the Resource, HTTP Request method like POST, GET, PUT, PATCH, or DELETE.
then() — We validate the response i.e the response code, response time, response message, response headers, response body, etc.
It is important to keep in mind that REST Assured supports Given/When/Then BDD syntax. Thus, test cases can be easily understood and written.In the assertion statement, the "hasSize()" function is used. Using the "hasSize()" method, we count the number of circuits and decide whether there are more than 20 of them.
The verification performs the following functions.
- The JSON response is captured.
- Make a query for all items with circuitId.
- Checks whether the result contains 20 circuitId or not.
There are other more Hamcrest matchers/assertors, such as "equalTo()", "lessThan()", "greaterThan()", "hasItem()", and so on. You might find the Hamcrest documentation at http://hamcrest.org/JavaHamcrest/ helpful .
In addition to the response body, other characteristics are being validated.REST Assured checks not only the response body but also technical elements of the response such as HTTP status code, response content type, and headers.
Let's look at an example of a test script for them.
@Test
public void headersAndStatus() {
given().
when().get("http://ergast.com/api/f1/2017/circuits.json").
then().
assertThat().
statusCode(200).
and().contentType(ContentType.JSON).
and().header("Content-Length",equalTo("4567"));
}
A second thing to note is how easy it is to concatenate two assertions using the and() method, which makes the code more understandable.
Parameterization of our test
This is where the idea of Data-Driven Testing comes into play. The RESTful API accepts two sorts of arguments.
- Query Parameter
- Path Parameter
Query parameters: These are appended to the RESTful API endpoint.
Path parameter: The path to the API endpoint.
Both sorts of parameters are supported by REST Assured. Let's look at an example script for this.
For query parameter:
@Test
public void something() {
String originalText = "test";
String trueValue = "md5";
given().
param("text",originalText).
when().
get("http://md5.jsontest.com").
then().
assertThat().
body("md5",equalTo(trueValue));
}
For Path Parameter:
@Test
public void CircuitsShouldBe20() {
String season = "2017";
int numberOfRaces = 20;
given().
pathParam("raceSeason",season).
when(). get("http://ergast.com/api/f1/{raceSeason}/circuits.json").
then().assertThat().
body("MRData.CircuitTable.Circuits.circuitId",hasSize(numberOfRaces));
}
Path parameters are defined using the pathParam() function rather than the param() method.
REST Assured also has a lot of additional features.
- For example, it can deserialize POJOs. This can be used to serialize the attributes and values of a Java object instance into a JSON or XML document, which is then sent to a RESTful API by using the POST function.
- Requests and responses are recorded. When inspecting API answers to establish appropriate checks or when ensuring that your API request is accurate, this is very useful.
Rest Assured Automation Testing with TestNG:
The 'TestNG' framework is inspired by junit. This is the most recent Rest Assured framework. You can construct testcases in groups or as dependencies on another function. NG stands for 'NEXT GENERATION'.
The TestNG framework is an important part of the development of test automation frameworks that use the Java programming language. TestNG is a user-friendly automation framework that solves JUnit's shortcomings and limitations. As a result, it gains a whole new set of features, making it more powerful and valuable. It makes it easier to design tests that are more flexible and powerful. This is an open-source framework for testing APIs and UIs
Here are some benefits of using TestNG Unit Testing Framework:
- Test case creation is made easier
- Groups the test cases
- Prioritizes the test cases
- Executes the test cases
- Generates logs
- Generates reports
- Reads keywords/data from the excel files
- Supports parameterization
- Supports parallel execution of tests
TestNG- Handle Multiple Test Cases:
We must run all of the test cases at the conclusion of the test. The test cases are interdependent. TestNG provides the ability to run these test cases concurrently
It is necessary to create a file called testing.xml that will handle many test scenarios.
Testing.xml:
<suite name ="Test-suite">
<test name = "testng">
<classes>
<class name = "automationframework.something"/>
<class name = "automationframework.CircuitsShouldBe20"/>
</classes>
</test>
</suite>
The XML code is pretty basic. Our first step is to create a suite> tag to define the test suite name, and then to write a tag to describe the test name. The test suite and test cases may be named however we like, but the tag name is a combination of the package name and the test name.
Conclusion:
Since API Testing is a critical part of any development life cycle, REST Assured Framework is one of the most widely used Web Services Testing tools in Java. Advanced features, along with simplicity in implementation, make it a must for any testers to ensure quality in the end product. With its fluent approach and the expressive method names, it makes the call and its output easily understandable. Both JSONPath and Matchers further increase the power and expressiveness.
References:
- Johan Haleby(2010, December), REST Assured: https://rest-assured.io/
- Johan Haleby(2015, Jul 20), Rest-assured usage: https://github.com/rest-assured/rest-assured/wiki/Usage
- TestNG Documents: https://testng.org/doc/
Join us
Scalability, reliability and maintainability are the three pillars that govern what we build at Halodoc Tech. We are actively looking for engineers at all levels and if solving hard problems with challenging requirements is your forte, please reach out to us with your resumé at careers.india@halodoc.com.
About Halodoc
Halodoc is the number 1 all around Healthcare application in Indonesia. Our mission is to simplify and bring quality healthcare across Indonesia, from Sabang to Merauke. We connect 20,000+ doctors with patients in need through our Tele-consultation service. We partner with 3500+ pharmacies in 100+ cities to bring medicine to your doorstep. We've also partnered with Indonesia's largest lab provider to provide lab home services, and to top it off we have recently launched a premium appointment service that partners with 500+ hospitals that allow patients to book a doctor appointment inside our application. We are extremely fortunate to be trusted by our investors, such as the Bill & Melinda Gates Foundation, Singtel, UOB Ventures, Allianz, GoJek, Astra, Temasek and many more. We recently closed our Series C round and In total have raised around USD$180 million for our mission. Our team works tirelessly to make sure that we create the best healthcare solution personalized for all of our patient's needs, and are continuously on a path to simplify healthcare for Indonesia.