NashTech Insights

Everything you need to know about building an API Testing framework with Rest Assured

Anshita Mathur
Anshita Mathur
Table of Contents

Hi Everyone,
This blog will use Rest Assured to build a robust API automation testing framework. For this, we’ll implement the Data Driven Testing approach and create testing reports for it.

The Objective of Designing a Framework

We will need to keep a wide variety of files when automating test cases, including various endpoints, URLs, data-driven test cases, reports, etc. The main objective of Designing a Framework is Reusability, Maintainability, and Readability so that we can create a robust API automation testing framework using Rest Assured.

Rest Assured Framework Workflow

This is the Rest Assured Framework Design workflow, we divide the entire framework into three different parts-

  • Development
  • Execution
  • Continuous Integration (CI)
Rest Assured Framework Design workflow
  1. EndPoints – We will maintain all the Routes and Endpoints in a single package with different classes. In Routes, we define all the URLs related to our module, and in Endpoints, there will be an implementation of the particular request.
  2. Endpoints will be called by Test Cases and once you design the Test cases, the test cases will be executed by the testng.xml file
  3. We will create one more package called payload, in the payload, we will maintain all the POJO (plain old Java object) like for every model we will create a POJO class to create data.
  4. The utility is required primarily for Data-Driven Testing, this package is used for the Data Provider, Extent Report class.
  5. After the Development and Execution part, we will push the entire code into Git and Github repositories and then run through Jenkins.

To test the APIs, we are going to use a testing Swagger https://petstore.swagger.io/

Project Structure

  • First, we need to create a new Maven project.
  • Create your packages and classes, Folder structure will look like this-
  • Update the pom.xml file as well with the necessary dependencies-
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>RestAssuredFramework</artifactId>
    <version>1.0-SNAPSHOT</version> 
    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
            <dependency>
                <groupId>io.rest-assured</groupId>
                <artifactId>rest-assured</artifactId>
                <version>5.3.0</version>
            </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-path</artifactId>
            <version>5.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.7.1</version>
            <scope>test</scope>
        </dependency>
        <dependency> 
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>5.0.9</version>
        </dependency>
    </dependencies>
</project>

Steps to Test APIs using Rest Assured Automation Framework

In the Routes.java class, we will maintain only the URLs and we will get these URLs from the Swagger UI which I mentioned earlier.

package api.endpoints;
public class Routes {
    public static String base_URL = "https://petstore.swagger.io/v2";
    public static String post_URL = base_URL+"/user";
    public static String get_URL = base_URL+"/user/{username}";
    public static String update_URL = base_URL+"/user/{username}";
    public static String delete_URL = base_URL+"/user/{username}";
}
  • Now, we will implement the methods for sending these requests to the user service like the CRUD method implementation, we will implement these methods in UserEndPoints.java class-
package api.endpoints;
import static io.restassured.RestAssured.given;
import api.payload.User;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
public class UserEndPoints {
    public static Response createUser(User payload){
         Response response = given()
                 .contentType(ContentType.JSON)
                 .accept(ContentType.JSON)
                 .body(payload)

                 .when()
                 .post(Routes.post_URL);
         return response;
    }
    public static Response readUser(String userName){
        Response response = given()
                .pathParam("username",userName)

                .when()
                .get(Routes.get_URL);
        return response;
    }
    public static Response updateUser(String userName, User payload){
        Response response = given()
                .contentType(ContentType.JSON)
                .accept(ContentType.JSON)
                .pathParam("username", userName)
                .body(payload)

                .when()
                .put(Routes.update_URL);
        return response;
    }
    public static Response deleteUser(String userName){
        Response response=given()
                .pathParam("username",userName)
        .when()
                .delete(Routes.delete_URL);
        return response;
    }
}
  • Next, we will create a User Payload class, for this, we have to know what variables are there in the user field. First, we will define the variables and then we will create setters and getters automatically.
 int id;
    String userName;
    String firstName;
    String lastName;
    String email;
    String password;
    String phone;
  • To automatically generate the Getters and Setters for these variables, just select them and go to code and click on Generate option.
  • Now, simply click on Getter and Setter option, this will automatically generate get() and set() methods for every selected variable-

Data-Driven Testing Approach for Rest-Assured Automation Framework

  • Now we just need to call the EndPoints methods in the Test class we’ll be creating. And for this, we’re implementing a data-driven testing strategy. Maintaining the Excel sheet containing the data, the Apache POI, and the Excel Utility file are prerequisites for creating a data-driven test case.
  • Here, we are using a combination of Excel utility along with the DataProvider, DataProvider will get the entire data from the Excel sheet and put the data in an array and pass the data to the test method, and the test method will repeat n no. of times without using any looping statements. So that we can use different sets of data in our tests.
  • This is my DataProvider class, I created two DataProviders here-
package api.utilities;
import org.testng.annotations.DataProvider;
import java.io.IOException;
public class DataProviders {
    @DataProvider(name = "testdata")
    public static Object[][] getAllData() throws IOException{
        String path = System.getProperty("user.dir")+"//testData//User-data (1).xlsx";
        Utility xl = new Utility(path);
        int rowNum = xl.getRowCount("Sheet1");
        int colNum = xl.getCellCount("Sheet1", 1);
        String apiData[][] = new String[rowNum][colNum];
        for (int i=1;i<=rowNum;i++){
            for (int j=0;j<colNum;j++){
                apiData[i-1][j] = xl.getCellData("Sheet1",i,j);
            }
        }
        return apiData;
    }
    @DataProvider(name = "UserNames")
    public static String[] getUserNames() throws IOException{
        String path = System.getProperty("user.dir")+"//testData//User-data (1).xlsx";
        Utility xl = new Utility(path);
        int rowNum = xl.getRowCount("Sheet1");
        String apiData[] = new String[rowNum];
        for (int i=1;i<=rowNum;i++){
                apiData[i-1] = xl.getCellData("Sheet1",i,1);
        }
        return apiData;
    }
}
  • Now, I’m writing tests for POST and DELETE user requests, for POST request we are going to refer to our first DataProvider getAllData(), and for DELETE request, we will refer to this second DataProvider getUserNames() which will be going to delete the users which are created in the first request by their usernames.
public class DDTests {
    @Test(priority = 1, dataProvider = "testdata", dataProviderClass = DataProviders.class)
    public void testPostUsers(String userName, String fName, String lName, String email, String pwd, String ph){
        User userPayload = new User();
        userPayload.setUserName(userName);
        userPayload.setFirstName(fName);
        userPayload.setLastName(lName);
        userPayload.setEmail(email);
        userPayload.setPassword(pwd);
        userPayload.setPhone(ph);
        Response response = UserEndPoints.createUser(userPayload);
        Assert.assertEquals(response.getStatusCode(),200);
        System.out.println(response.prettyPrint());
        System.out.println("User Created Successfully");
    }

    @Test(priority = 2, dataProvider = "UserNames", dataProviderClass = DataProviders.class)
    public void testDeleteUsers(String userName){
        Response response = UserEndPoints.deleteUser(userName);
        Assert.assertEquals(response.getStatusCode(),200);
        System.out.println("User Deleted Successfully");
    }
}
  • After the Development of Test cases, we need to Execute our test cases. So we will generate Extent Report now. For this first, we need to create the Extent Report Utility class and also the testng.xml file. And we will keep this Utility file inside the testng.xml file like this-
<listeners>
        <listener class-name="api.utilities.ExtentReportManager" />
</listeners>
  • The generated report will look like this-

In conclusion, We are successfully able to automate the POST and DELETE requests using the rest-assured framework.

I hope you had a good read. Thank you!

Reference

https://rest-assured.io/#docs

Anshita Mathur

Anshita Mathur

I am Software Consultant - QA at Nashtech Global. I have completed my B.Tech from Jodhpur Institute of Engineering and Technology. I am familiar with the core concepts of Manual and Automation Testing and tools such as Postman, Selenium, Appium, and Gatling. I am looking forward to roles that will help me realize my potential by exploring the various aspects of this field.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: