NashTech Insights

Managing data in Rest-Assured with CI/CD:Best Practices and tips

Soniya Raichandani
Soniya Raichandani
Table of Contents

In this blog, we will look into how we can manage the date in Rest Assured(Curd operations) with Gitlab-CI/CD

Rest Assured is a Java package that is used for API testing and it is also a Java library that supports JSON and XML-based Web services, also supports CRUD requests and can be used to validate and verify the responses to these requests. It is used to invoke REST web services and check responses. We can be integrated this with JUnit and TestNG framework and it is implemented in Groovy. Groovy is a language.

Why do we need Rest Assured?

Using Rest Assured, automation testing of APIs, and sending simple HTTP requests with user-friendly customizations is simple. It is necessary to understand API testing and integration testing and provides very good confidence on the backend, allowing front-end testing to focus solely on the UI and client-side operations. It is open source, and adding many new methods and libraries has made it an excellent choice for API automation.

Manage data with RestAssured’s API

How to create multiple data in Rest Assured with TestNG and Rest Assured is a Domain-specific Language so it doesn’t require writing the test cases in data-driven format because it considers the ability of a single test that can be executed multiple times with different sets of input and validation parameters. However, easy to uses a mechanism to create data-driven tests through the use of the DataProvider mechanism.

Data Provider

A Data Provider is a method on your class that returns an array of objects.  This method is annotated with @DataProvider.mData provider returns two dimensional. An Array of objects  (Object[][]) where the first dimension’s size is the number of times the test method will be invoked and the second dimension size contains an array of objects that must be compatible with the parameter types of the test method. A @Test method specifies its Data Provider with the dataProvider attribute. If you do not define a name for the DataProvider, the DataProvider method name is considered its default name, the name of it calls the DataProvider method.
By default, the data provider will be looked for in the current test class or one of its base classes. If you want to put your data provider in a different class, it needs to be a static method or a class with a non-arg constructor, and you specify the class where it can be found in the data provider class attribute.

Data-Driven

Data-driven testing using Rest Assured, I have created a TestNG class, and I am feeding the data from an excel file to my code and performing the test. I have written my script in BDD format which makes it easy to understand.

Before Integrate with Gitlab, we need to install prerequisites like-
1. Rest Assured
2. Java 11
3. Maven
4. TestNG
5. GitLab Account

Create a Maven Project for Rest Assured

Step 1: Open IDE
Step 2: Create a Maven Project

Configure TestNG & REST Assured

After creating your maven project add dependencies in pom.xml.

Maven dependency for rest assured 
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>
Maven dependency for testng
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.1.0</version>
    <scope>test</scope>
</dependency>

Let’s see how to automate CRUD operations with its help of it.

Example -1 with Data Provider

Step 1: Create Java class under the test folder

TestApi.java

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
public class TestApi {

    //data provider annotation
    @Test(dataProvider="Title")
    void dataProvPayLoad(String title, String body) {

        //base URL
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        //input details
        given().header("Content-type", "application/json")

                //adding post method with parameterization from data provider
                .body(Payload.postBody(title, body)).
                when().post("/posts").then()

                //verify status code as 201
                .assertThat().statusCode(201);
    }

    //data provider method
    @DataProvider(name="Title")
    public Object[][] getData() {
        //multi-dimension element collection with two data sets
        return new Object[][]
                {{"Cypress","JavaScript"},{"Selenium","Python"}};
    }
}

You can use static Import for RestAssured – import static io. restassured.RestAssured*; then direct get the URL.
Response response= get(“https://reqres.in/api/users?page=2&#8221;);

Payload.java

public class Payload {
    public static String postBody(String title, String body) {
        //request payload
        String b = "{" +
                //Parameterizing title and body fields
                "\"title\": \"" +title+ " \"," + "\"body\": \"" +body+ " \"," + " \"userId\": \"34\" }";
        return b;
    }
}

Output in Console

Example-2 with Data-Driven

1. Create a TestNG class under the respective package in the Maven project and set the base URI and base Path.

2. Create a method to post new programs under @Test annotation passing the parameter from the data provider method.

3. Create a method under @DataProvider annotation to get the data from Excel.

4. After that run the script and verify whether the test has passed or not.

@DataProvider(name = "progdata")
String[][] get_prog_data() throws IOException {
String path = System.getProperty("user.dir") + "/src/test/java/DataDrivenTesting/Data.xlsx";
int rownum = XLUtils.getRowCount(path, "Sheet1");
int colnum = XLUtils.getCellCount(path, "Sheet1", 1);
String progdata[][] = new String[rownum][colnum];
for (int i = 1; i <= rownum; i++) 
{
for (int j = 0; j < colnum; j++) 
{
progdata[i - 1][j] = XLUtils.getCellData(path, "Sheet1", i, j);
}
}
return progdata;
}

Testing Restful Services with Best Practices

There are libraries and best practices helping you to keep your integration tests concise, clean, decoupled and maintainable. There are some best practices that we need to follow-

  • Invest in readable and maintainable tests. If you let your tests rot you will sentence your service to death.
  • Don’t depend on the internals of the RESTful service under test (service classes, database schema). This makes your tests brittle.
  • Use POJOs and object mapping
  • Use libraries because Rest-Assured to fluently create HTTP requests and assertions about the response.
  • Create a RequestSpecification to reuse request configurations (base URL, parameters, content type, debugging logging) that you want to use for all requests.

Integrate the RestAssured with GitLab

Step 1: Create a Repository. Before that need to log in with Gitlab if you don’t have an account with Gitlab so first of all create a new account and then login in that. After that create a new project.
Step 2: Push the project from the local to the Gitlab Repository.
Step 3:  Create .gitlab-ci.yml file in the project in GitLab

image: adoptopenjdk/maven-openjdk11
 
stages:
  - test
 
variables:
  MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
 
test:
  stage: test
  allow_failure: true
 
# Run the tests
  script:
    - mvn $MAVEN_OPTS clean package
    - mvn compile test
 
# Store artifacts
  artifacts:
    when: always
    name: "report"
    paths:
    - target/surefire-reports/*
    expire_in: 1 h

Conclusion-

Rest Assured enables you to test REST APIs using Java libraries and integrates well with Maven. It can be easily integrated with Gitlab as well as maintain the date with the help of data providers and data-driven.

References-

https://www.ontestautomation.com/creating-data-driven-api-tests-with-rest-assured-and-testng/
https://www.programsbuzz.com/article/data-driven-api-tests-rest-assured-and-testng

Soniya Raichandani

Soniya Raichandani

Hi there! My name is Soniya Raichandani and I'm a Software tester with over 4.5 years experience.I have worked with a variety of testing methodologies and tools, including manual and automated testing, regression testing, and performance testing.I created this blog to share my knowledge and experiences with the testing community. My goal is to help other testers improve their skills and stay up-to-date with the latest trends in software testing.

Leave a Comment

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

Suggested Article

%d bloggers like this: