Understanding API Testing: Benefits and Challenges

HOME

Interview Questions for API Testing 2025

HOME

https://www.qaautomation.expert
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html
  {
     "username": "exampleuser",
     "password": "examplepassword"
   }
   

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
 x-api-key: YOUR_API_KEY

'or 1=1--
"and 1=1--
echo "malicious" >> /var/www/html/index.html
rm file.txt; cat /etc/passwd

https://api.example.com/items?page=2&limit=50
https://api.example.com/products?category=electronics&price<1000

name: API Tests

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Set up Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '14'

    - name: Install Newman
      run: npm install -g newman

    - name: Run API tests with Newman
      run: newman run test.json

{
  "token": "eyJhbGciOiJIUzI1NiIsInR..."
}

import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class APITests {

        String BaseURL = "https://reqres.in/api";

    @Test
    public void getUser() {  

        // GIVEN
        given()
                .contentType(ContentType.JSON)

                // WHEN
                .when()
                .get(BaseURL + "/users/2")

                // THEN
                .then()
                .statusCode(200)
                .body("data.first_name", equalTo("Janet"))
                .log().all();

    }

}

Use Case Examples**:
  - Login authentication: The client needs the server's response before proceeding.
  - Fetching data: The client requires the result immediately to display to the user.
**Use Case Examples**:
  - File upload or processing: The server processes the file and sends a notification when done.
  - Notification systems: Sending push notifications to multiple devices.

How to handle async requests in API Testing

HOME

<dependency>
            <groupId>org.asynchttpclient</groupId>
            <artifactId>async-http-client</artifactId>
            <version>3.0.0.Beta3</version>
</dependency>

package org.example;

import com.jayway.jsonpath.JsonPath;
import org.asynchttpclient.Dsl;
import org.asynchttpclient.Response;
import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import static org.hamcrest.MatcherAssert.assertThat;


public class AsyncRequest_Demo {

    @Test
    public void verifyResponse() throws ExecutionException, InterruptedException {
         Future<Response> futureResponse = Dsl.asyncHttpClient().prepareGet("https://reqres.in/api/users?delay=5").execute();
         Response response = futureResponse.get();

         System.out.println("Response :" + response);

         Assert.assertEquals(200, response.getStatusCode());
         Assert.assertTrue(response.toString().contains("george.bluth@reqres.in"));

    }
}

How to parse XML in Java

HOME

<?xml version = "1.0"?>
<department>
    <employee id = "10001">
        <firstname>Tom</firstname>
        <lastname>Mathew</lastname>
        <salary>25000</salary>
        <age>21</age>
    </employee>

    <employee id = "20001">
        <firstname>Katherine</firstname>
        <lastname>Jason</lastname>
        <salary>15000</salary>
        <age>20</age>
    </employee>

    <employee id = "30001">
        <firstname>David</firstname>
        <lastname>Mathew</lastname>
        <salary>35000</salary>
        <age>25</age>
    </employee>

    <employee id = "40001">
        <firstname>Berry</firstname>
        <lastname>Brian</lastname>
        <salary>50000</salary>
        <age>30</age>
    </employee>
</department>
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("employee");
System.out.println("Node Length :" + nodeList.getLength());
for (int temp = 0; temp < nodeList.getLength(); temp++) {

        Node node = nodeList.item(temp);
        System.out.println("\nCurrent Element :" + node.getNodeName());

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;

             //returns specific attribute
              System.out.println("Employee Id : " + eElement.getAttribute("id"));

            //returns a list of subelements of specified name
             System.out.println("First Name: " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
             System.out.println("Last Name: " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
             System.out.println("Salary: " + eElement.getElementsByTagName("salary").item(0).getTextContent());
             System.out.println("Age: " + eElement.getElementsByTagName("age").item(0).getTextContent());

    }

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class XMLParser {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test.xml");
            System.out.println("Request :" + inputFile);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            //Extract the root element
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nodeList = doc.getElementsByTagName("employee");
            System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < nodeList.getLength(); temp++) {

                Node node = nodeList.item(temp);
                System.out.println("\nCurrent Element :" + node.getNodeName());

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node;

                    //returns specific attribute
                    System.out.println("Employee Id : " + eElement.getAttribute("id"));

                    //returns a list of subelements of specified name
                    System.out.println("First Name: " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                    System.out.println("Last Name: " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                    System.out.println("Salary: " + eElement.getElementsByTagName("salary").item(0).getTextContent());
                    System.out.println("Age: " + eElement.getElementsByTagName("age").item(0).getTextContent());

                }
            }

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

}

<?xml version = "1.0"?>
<cars>
    <sportscar company = "Porsce">
        <carname type = "formula one">Porsche 718 Boxster</carname>
        <carname type = "sports car">Porsche 718 Cayman</carname>
        <carname type = "sports car">2024 Porsche Panamera</carname>
    </sportscar>

    <supercars company = "Lamborgini">
        <carname>Lamborghini Aventador</carname>
        <carname>Lamborghini Reventon</carname>
        <carname>Lamborghini Gallardo</carname>
    </supercars>

    <supercars company = "Audi">
        <carname>Audi R8</carname>
        <carname>Audi Q8</carname>
        <carname>Audi Q6 e-tron</carname>
    </supercars>
</cars>

package com.example.XML;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class ComplexXMLParser {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test4.xml");
            System.out.println("Request :" + inputFile);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            //Extract the root element
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList sportscarNodeList = doc.getElementsByTagName("sportscar");
           // System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < sportscarNodeList.getLength(); temp++) {

                Node node = sportscarNodeList.item(temp);
                System.out.println("\nCurrent Element :" + node.getNodeName());

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node;

                    //returns specific attribute
                    System.out.println("sportscar : " + eElement.getAttribute("company"));

                    NodeList sportcarNameList = eElement.getElementsByTagName("carname");

                    for (int count = 0; count < sportcarNameList.getLength(); count++) {
                        Node node1 = sportcarNameList.item(count);

                        if (node1.getNodeType() == node1.ELEMENT_NODE) {
                            Element car = (Element) node1;

                            System.out.print("\ncar type : " + car.getAttribute("type"));
                            System.out.print("\ncar name : " + car.getTextContent());

                        }
                    }
                }

            }

            System.out.println("\n====================================================");
            NodeList supercarsNodeList = doc.getElementsByTagName("supercars");
            // System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < supercarsNodeList.getLength(); temp++) {

                Node node1 = supercarsNodeList.item(temp);
                System.out.println("\nCurrent Element :" + node1.getNodeName());

                if (node1.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node1;

                    //returns specific attribute
                    System.out.println("supercars : " + eElement.getAttribute("company"));

                    NodeList supercarsNameList = eElement.getElementsByTagName("carname");

                    for (int count = 0; count < supercarsNameList.getLength(); count++) {
                        Node node2 = supercarsNameList.item(count);

                        if (node1.getNodeType() == node2.ELEMENT_NODE) {
                            Element car = (Element) node2;

                            System.out.print("car name : " + car.getTextContent()+"\n");

                        }
                    }
                }

            }

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

}

How to retrieve XML Child Nodes in Java

HOME

<?xml version = "1.0"?>
<department>
    <employee>
        <firstname>Tom</firstname>
        <lastname>Mathew</lastname>
        <salary>25000</salary>
        <age>21</age>
    </employee>
</department>
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("employee");
System.out.println("Node Length :" + nodeList.getLength());
for (int temp = 0; temp < nodeList.getLength(); temp++) {
                Node node = nodeList.item(temp);
                System.out.println("\nCurrent Element :" + node.getNodeName());
  NodeList childNodes = node.getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node childNode = childNodes.item(i);
                    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("Child node name " + i + ":" + childNode.getNodeName());
                        System.out.println("Child node value: " + i + ":" + childNode.getTextContent());

                    }
                }

package com.example.XML;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class ChildNodes {

    public static void main(String[] args) {

        try {
            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test1.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            //Extract the root element
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nodeList = doc.getElementsByTagName("employee");
            System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < nodeList.getLength(); temp++) {
                Node node = nodeList.item(temp);
                System.out.println("\nCurrent Element :" + node.getNodeName());

                NodeList childNodes = node.getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node childNode = childNodes.item(i);
                    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("Child node name " + i + ":" + childNode.getNodeName());
                        System.out.println("Child node value: " + i + ":" + childNode.getTextContent());

                    }
                }
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }

    }
}

<?xml version = "1.0"?>
<department>
    <employee>
        <firstname>Tom</firstname>
        <lastname>Mathew</lastname>
        <salary>25000</salary>
        <age>21</age>
    </employee>

    <employee id = "429">
        <firstname>Erika</firstname>
        <lastname>David</lastname>
        <salary>
                <fixed>
                    <fixed1>350000</fixed1>
                    <fixed2>200000</fixed2>
                </fixed>
                <bonus>5000</bonus>
        </salary>
        <age>29</age>
        <type>Permanent</type>
    </employee>
</department>

package com.example.XML;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class ComplexChildNodes {

    public static void main(String[] args) {

        try {
            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test2.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            //Extract the root element
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nodeList = doc.getElementsByTagName("employee");
            System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < nodeList.getLength(); temp++) {
                Node node = nodeList.item(temp);
                System.out.println("\nCurrent Element :" + node.getNodeName());

                NodeList childNodes = node.getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node childNode = childNodes.item(i);

                    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("Child node name " + i + ":" + childNode.getNodeName());
                        System.out.println("Child node value: " + i + ":" + childNode.getTextContent());

                        for (int j = 0; j < childNode.getChildNodes().getLength(); j++) {
                            Node subChildNode = childNode.getChildNodes().item(j);
                            if (subChildNode.getNodeType() == Node.ELEMENT_NODE) {
                                {
                                    System.out.println("Sub Child node name " + j + ":" + subChildNode.getNodeName());
                                    System.out.println("Sub Child node value: " + j + ":" + subChildNode.getTextContent());
                                }
                            }
                        }
                    }

                }
            }

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }

    }
}

Serialization – How to create JSON Payload from Java Object – Jackson API

HOME

In this tutorial, I will explain the creation of JSON Object Payload with the help of POJO (Plain Old Java Object).

What is POJO?

POJO stands for Plain Old Java Object. It is a very simple object, and it has no bounds or we can say that it has no restrictions other than the Java language specification. Also, it does not require any classpath.

A big advantage of POJO is it increases the readability and reusability of our project code and developers find it easy when understanding the code. Also, POJO is easy to write and anyone can understand them easily.

Now let’s deep dive into some technical terms about the POJO. Below are a few points about the POJO are:

  1. A POJO should not have to extend prespecified classes.
  2. Secondly, a POJO should not have implemented any prespecified interface.
  3. Lastly, POJO should not contain prespecified annotations

A POJO class can follow some rules for better usability. These rules are:-

  1. Each variable should be declared as private just to restrict direct access.
  2. Each variable that needs to be accessed outside class may have a getter, a setter, or both methods. If the value of a field is stored after some calculations, then we must not have any setter method for that.
  3. It Should have a default public constructor.
  4. Can override toString(), hashcode, and equals() methods.

POJO classes are extensively used for creating JSON and XML payloads for API.

In the below example, let me create a simple JSON with some nodes which is actually a 1:1 mapping i.e. each key has a single value, and the type of values is mixed.

{
  "firstName" : "Vibha",
  "lastName" : "Singh",
  "age" : 30,
  "salary" : 75000.0,
  "designation" : "Manager",
  "contactNumber" : "+91999996712",
  "emailId" : "abc123@test.com"
}

Let us create variables in the POJO class now for the above JSON. Now, a class name Employee will be created with the private data members as mentioned in the above JSON. Since we have created all variables as private, then there should be a way to manipulate or retrieve these data. So we create the corresponding getter and setter methods for these data members.

It is very tedious to create getter and setter methods for all the data members for big JSON strings.  Every IDE gives you a shortcut to generate getter and setter methods.  Here, I am using Eclipse and creating these getter and setter methods.

Select all the data members and Right-click on the page. Then select Source and then select Generate Getter and Setter methods.

This opens a new screen as shown below.

You can select the data member for which you want to create the getter and setter method. I want to create the getter and setter methods for all the data members, so click on Select All and then click on the Generate Button. This will generate the getter and setter methods for all the data members.

Below is the sample code of the Employee table, which contains the data members needed for Employee JSON and their corresponding getter and setter methods.

public class Employee {

	// private variables or data members of POJO class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}
	
	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

Using the above POJO class, you can create any number of custom Employee objects and each object can be converted into a JSON Object and Each JSON object can be parsed into Employee POJO.

We will create a JSON object from POJO and vice versa now, which is generally called serialization and deserialization using Jackson APIs.

Serialization – Serialization is a process where you convert an Instance of a Class (Object of a class) into a Byte Stream. Here, we are converting Employee class object to JSON representation or Object

Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a JSON Object to an Employee class object.

We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

What is ObjectMapper ?

ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content and to support more advanced object concepts such as polymorphism and object identity.

Now, let us create a Test Class to show Serialization.

public class EmployeeTest {

	@Test
	public void serializationTest()  {

		Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");

		// Converting a Java class object to a JSON payload as string
		ObjectMapper mapper = new ObjectMapper();
		String employeeJson = mapper.writeValueAsString(employee);
		String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
		System.out.println(employeeJson);
		System.out.println(employeePrettyJson);
   }
}try {
			String employeeJson = mapper.writeValueAsString(employee);
			System.out.println(employeeJson);
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}	
	}

The output of the above program is

Here, ObjectMapper from fasterxml.jackson.databind is used for Serialization.

writeValueAsString() is a method that can be used to serialize any Java value as a String.

writerWithDefaultPrettyPrinter() is used to pretty-print the JSON output. It is a Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation.

I hope this has helped to clear your doubts regarding POJO and how to create JSON objects using POJO.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Introduction to Rest Assured

HOME

In this tutorial, I’ll explain about API & Rest Assured.

What is API?

API stands for Application Programming Interface. It comprises a set of functions that can be accessed and executed by another software system.  Thus, it serves as an interface between different software systems and establishes their interaction and data exchange. APIs can be used in various contexts, including web development, mobile app development, and software integration. For example, web APIs allow websites to interact with external services, such as third-party payment services or storing the information in a database.

What is API Testing?

In the modern development world, many web applications are designed based on a three-tier architecture model. These are 

  1. Presentation Tier – User Interface (UI
  2. Logic Tier – Business logic is written in this tier. It is also called Business Tier. (API
  3. Data Tier – Here information and data are stored and retrieved from a Database. (DB) Ideally, these three layers (tiers) should not know anything about the platform, technology, and structure of each other.

 We can test UI with GUI testing tools, and we can test logic tier (API) with API testing tools. The logic tier comprises all the business logic, and it has more complexity than the other tiers the test executed on this tier is called API Testing. API Testing tests the logic tier directly and checks expected functionality, reliability, performance, and security.

What is Rest API?

REST is an architectural style that uses simple HTTP calls for inter-machine communication. REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier, and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource.

REST API Testing with Rest Assured

What is Rest Assured?

REST Assured is a Java DSL for simplifying the 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.

Rest-Assured library also provides the ability to validate the HTTP Responses received from the server. For e.g. we can verify the Status code, Status message, Headers, and even the Body of the response. This makes Rest-Assured a very flexible library that can be used for testing.

REST Assured can be used to test XML as well as JSON-based web services. REST Assured can be integrated with JUnit and TestNG frameworks for writing test cases for our application.

HTTP Methods for REST API Automation Testing

REST API uses five HTTP methods to request a command:

GET: To retrieve the information at a particular URL.

PUT: To update the previous resource or create new information at a particular URL.

PATCH: For partial updates.

POST: It is used to develop a new entity. Moreover, it is also used to send information to the server, such as uploading a file, customer information, etc.

DELETE: To delete all current representations at a specific URL.

HTTP Status Codes

Status codes are the responses given by a server to a client’s request. They are classified into five categories:

  1. 1xx (100 – 199): The response is informational
  2. 2xx (200 – 299): Assures successful response
  3. 3xx (300 – 399): You are required to take further action to fulfill the request
  4. 4xx (400 – 499): There’s a bad syntax and the request cannot be completed
  5. 5xx (500 – 599): The server entirely fails to complete the request

Advantages of Rest Assured

  1. It is an Open source Tool i.e. free.
  2. It requires less coding compared to Apache Http Client.
  3. Easy parsing and validation of response in JSON and XML.
  4. The extraction of values and asserting is quite easy using inbuilt Hemcrest Matchers.
  5. It follows BDD keywords like given(), when(), then() which makes code readable and supports clean coding. This feature is available from version 2.0.
  6. It supports quick assertion for status code and response time.
  7. It supports assertion to Status Code, Response Time, Headers, cookies, Content-Type, etc.
  8. It has a powerful logging mechanism.
  9. It can be easily integrated with other Java libraries like TestNG, JUnit as Test Framework and Extent Report, and Allure Report for reporting purposes.
  10. It provides quite good support for different authentication mechanisms for APIs.
  11. It can be integrated with Selenium-Java to achieve End-to-end automation.
  12. It supports JSONPath and XmlPath which helps in parsing JSON and XML response. Rest Assured integrates both by default.
  13. It can be used to verify JSON Schema using JSON Schema Validation library and XML schema validation
  14. It can be integrated with Build Tools like Maven or Gradle and supports CI/CD also.
  15. It supports multi-part form data and Spring Mock Mvc, Spring Web Test Client, Scala and Kotlin.

Integration of REST Assured with JUnit4

HOME

In this tutorial, I’ll create a Test Framework for the testing of REST API using REST Assured and JUnit4 as the test framework.

What is Rest Assured?

Rest Assured enables you to test REST APIs using java libraries and integrates well with Maven/Gradle. REST Assured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs.

What is JUnit?

JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. JUnit 4 is one of the most popular unit testing frameworks which has a significant role in the test-driven development process.

Dependency List:-

  1. REST Assured – 5.4.0
  2. Java 17
  3. JUnit – 4.13.2
  4. Maven – 3.9.6

Detailed Step Description

Step 1- Download and Install Java

Java needs to be present on the system to run the tests. Click here to know How to install Java. To know if Java is installed or not on your machine, type this command in the command line. This command will show the version of Java installed on your machine.

java -version

Step 2 – Download and setup Eclipse IDE on the system

The Eclipse IDE (integrated development environment) provides strong support for Java developers, which is needed to write Java code. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add a number of dependencies to the project. It is a very tedious and cumbersome process to add each dependency manually. So, to overcome this problem, we use a build management tool. Maven is a build management tool that is used to define project structure, dependencies, build, and test management. Click here to know How to install Maven.

To know if Maven is already installed or not on your machine, type this command in the command line. This command will show the version of Maven installed on your machine.

mvn -version

Step 4 – Create a new Maven Project

Click here to know How to create a Maven project

Below is the Maven project structure. Here,

Group Id – com.example
Artifact Id – RestAssured_JUnit4_Demo
Version – 0.0.1-SNAPSHOT
Package – com. example.RestAssured_JUnit4_Demo

Step 5 – Add REST Assured and JUnit4 dependencies to the project

Add the below-mentioned dependencies to the project.

<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>RestAssured_JUnit4_Demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>RestAssured_JUnit4_Demo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <rest-assured.version>5.4.0</rest-assured.version>
    <junit.version>4.13.2</junit.version>
    <json.version>20231013</json.version>
    <hamcrest.version>1.3</hamcrest.version>
    <maven.site.plugin.version>4.0.0-M13</maven.site.plugin.version>
    <maven.compiler.plugin.version>3.12.1</maven.compiler.plugin.version>
    <maven.surefire.plugin.version>3.2.3</maven.surefire.plugin.version>
    <maven.surefire.report.plugin.version>3.2.5</maven.surefire.report.plugin.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <dependencies>

    <!-- Rest-Assured Dependency -->
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>${rest-assured.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- JUnit4 Dependency -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- JSON Dependency -->
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>${json.version}</version>
    </dependency>

    <!-- Hamcrest Dependency -->
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-all</artifactId>
      <version>${hamcrest.version}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>${maven.site.plugin.version}</version>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin.version}</version>
        <configuration>
          <testFailureIgnore>true</testFailureIgnore>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven.compiler.plugin.version}</version>
        <configuration>
          <source>${maven.compiler.source}</source>
          <target>${maven.compiler.target}</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>${maven.surefire.report.plugin.version}</version>
      </plugin>
    </plugins>
  </reporting>
</project>

Step 6 – Create the TEST file

The tests should be written in src/test/java directory. To know how to create a JSON Request body using JSONObject, please refer to this tutorial.

import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static io.restassured.RestAssured.given;

public class APITests {

    String BaseURL = "https://dummy.restapiexample.com/api";


    @Test
    public void createUser() {

        JSONObject data = new JSONObject();

        data.put("employee_name", "NewUser1");
        data.put("employee_salary", "1000");
        data.put("employee_age", "35");

        // GIVEN
        given()
                .contentType(ContentType.JSON)
                .body(data.toString())

                // WHEN
                .when()
                .post(BaseURL + "/v1/create")

                // THEN
                .then()
                .statusCode(200)
                .body("data.employee_name", equalTo("NewUser1"))
                .body("message", equalTo("Successfully! Record has been added."));

    }

}

Step 7 – Test Execution through JUnit Test

Go to the Runner class and right-click Run As JUnit Test. The tests will run as JUnit tests. (Eclipse)

Below is the image to run the tests in IntelliJ.

This is how the execution console will look like.

Step 8 – Run the tests from the command line

Maven Site Plugin creates a folder – site under the target directory, and the Maven Surefire Report plugin generates the JUnit Reports in the site folder. We need to run the tests through the command line to generate the JUnit Report.

mvn clean test site

The output of the above program is

Step 9 – Report Generation

After the test execution, refresh the project, and a new folder with the name site in the target folder will be generated. This folder contains the reports generated by JUnit. The structure of the folder site looks as shown below.

Step 10 – View the Report

Right-click on the summary.html report and select Open In -> Browser ->Chrome.

Summary Report

Below is the summary Report.

Surefire Report

Below is an example of a Surefire Report. This report contains a summary of the test execution.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Integration of Serenity with Rest Assured

HOME

In this tutorial, I will explain the Integration of Serenity BDD with Rest Assured for the testing of RestFul API.

What is Serenity BDD?

Serenity BDD is an open-source library that aims to make the idea of living documentation a reality.

What is Rest Assured?

Rest Assured is one of the most powerful libraries for testing RESTful API using Java language. Rest-Assured is a Java-based library that is used to test RESTful Web Services. This library behaves like a headless Client to access REST web services. The rest-Assured library also provides the ability to validate the HTTP Responses received from the server. 

Prerequisite

  1. Java 17 installed
  2. Maven installed
  3. Eclipse or IntelliJ installed

Dependency List

  1. Java 17
  2. Maven – 3.9.5
  3. Serenity – 4.0.18
  4. Serenity Rest Assured – 4.0.18
  5. Rest Assured – 5.3.2
  6. JUnit – 4.13.2
  7. Maven Surefire Plugin – 3.1.2
  8. Maven Failsafe Plugin – 3.1.2
  9. Maven Compiler Plugin – 3.11.0

Project Structure

Step 1 – Update the Properties section in Maven pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <serenity.version>4.0.18</serenity.version>
    <serenity.maven.version>4.0.18</serenity.maven.version>
    <junit.version>4.13.2</junit.version>
    <rest.assured.version>5.3.2</rest.assured.version>
    <json.version>20231013</json.version>
    <maven.surefire.plugin.version>3.1.2</maven.surefire.plugin.version>
    <maven.failsafe.plugin.version>3.1.2</maven.failsafe.plugin.version>
    <maven.compiler.plugin.version>3.11.0</maven.compiler.plugin.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <tags></tags>
  </properties>

Step 2 – Add dependencies to POM.xml

<dependencies>
   <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-junit</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
      
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-screenplay-rest</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-rest-assured</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest.assured.version}</version>
            <scope>test</scope>
        </dependency>
         
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>  
  
       <dependency>
           <groupId>org.json</groupId>
           <artifactId>json</artifactId>
           <version>${json.version}</version>
        </dependency> 
        
    </dependencies>

Step 3 – Update the Build Section of pom.xml

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven.surefire.plugin.version}</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven.failsafe.plugin.version}</version>
                <configuration>
                    <includes>
                        <include>**/*.java</include>
                        <include>**/*.Tests</include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
           <plugin>
               <groupId>net.serenity-bdd.maven.plugins</groupId>
               <artifactId>serenity-maven-plugin</artifactId>
               <version>${serenity.version}</version>
               <dependencies> 
                  <dependency>
                       <groupId>net.serenity-bdd</groupId>
                       <artifactId>serenity-single-page-report</artifactId>
                       <version>${serenity.version}</version>
                  </dependency>                
               </dependencies>
               <configuration>
                   <tags>${tags}</tags>
                   <reports>single-page-html</reports> 
               </configuration>
               <executions>
                  <execution>
                      <id>serenity-reports</id>
                      <phase>post-integration-test</phase>
                      <goals>
                          <goal>aggregate</goal>
                      </goals>
                   </execution>
               </executions>
           </plugin>
        </plugins>
    </build>

Step 4 – Create the Test Code in src/java/test directory

There are 2 ways to create the same test. One approach is to have a Definition file that contains all the test code as shown below.

package org.example.tests;

import io.restassured.response.Response;
import net.serenitybdd.rest.SerenityRest;
import org.json.JSONObject;
import org.junit.Test;

import static org.hamcrest.Matchers.equalTo;

public class Employee {
    private static final String URL = "https://reqres.in/api";
    public Response response;

    int id = 2;

    @Test
    public void verifyValidUser() {

        response = SerenityRest
                .given()
                .contentType("application/json")
                .header("Content-Type", "application/json")
                .when()
                .get(URL + "/users/" + id);

        SerenityRest.restAssuredThat(response -> response.statusCode(200)
                .body("data.id", equalTo(2))
                .body("data.email", equalTo("janet.weaver@reqres.in"))
                .body("data.first_name", equalTo("Janet"))
                .body("data.last_name", equalTo("Weaver")));

    }

    @Test
    public void verifyCreateUser() {
        JSONObject data = new JSONObject();

        data.put("name", "Test");
        data.put("job", "Test Architect");

        response = SerenityRest
                .given()
                .contentType("application/json")
                .header("Content-Type", "application/json")
                .body(data.toString())
                .when()
                .post(URL + "/users");

        SerenityRest.restAssuredThat(response -> response.statusCode(201)
                .body("name", equalTo("Test"))
                .body("job", equalTo("Test Architect")));

    }

}

Another approach is that all tests are split into reusable blocks called “steps“. The main principle of the BDD approach is that we are trying to keep complexity to a high-level human-readable level. First of all, let’s create a separate package to keep our steps. It is always better to keep them separate as it shows which classes contain reusable components. It is better to make steps smaller. So let’s make separate reusable steps from our tests:

package org.example.steps;

import io.restassured.response.Response;
import net.serenitybdd.annotations.Step;
import net.serenitybdd.rest.SerenityRest;
import org.json.JSONObject;

import static org.hamcrest.Matchers.equalTo;

public class EmployeeSteps {
    private static final String URL = "https://reqres.in/api";
    public Response response;

    @Step("Search user by id {0}")
    public void sendUser(int id) {
        response = SerenityRest
                .given()
                .contentType("application/json")
                .header("Content-Type", "application/json")
                .when()
                .get(URL + "/users/" + id);

    }

    @Step("Create a new user")
    public void createUser() {

        JSONObject data = new JSONObject();

        data.put("name", "Test");
        data.put("job", "Test Architect");

        response = SerenityRest
                .given()
                .contentType("application/json")
                .header("Content-Type", "application/json")
                .body(data.toString())
                .when()
                .post(URL + "/users");

    }

    @Step("Verify the status code {0}")
    public void verifyStatusCode(int expectedStatusCode) {
        SerenityRest.restAssuredThat(response -> response.statusCode(expectedStatusCode));
    }

    @Step("Verify the user id {0}")
    public void verifyId(int expectedId) {
        SerenityRest.restAssuredThat(response -> response.body("data.id", equalTo(expectedId)));
    }

    @Step("Verify the user first name {0}")
    public void verifyFirstName(String expectedFirstName) {

        SerenityRest.restAssuredThat(response -> response.body("data.first_name", equalTo(expectedFirstName)));
    }

    @Step("Verify the user last name {0}")
    public void verifyLastName(String expectedLastName) {
        SerenityRest.restAssuredThat(response -> response.body("data.last_name", equalTo(expectedLastName)));
    }

    @Step("Verify the user email {0}")
    public void verifyEmail(String expectedEmail) {
        SerenityRest.restAssuredThat(response -> response.body("data.email", equalTo(expectedEmail)));
    }

    @Step("Verify the new user name {0}")
    public void verifyNewUserName(String expectedName) {
        SerenityRest.restAssuredThat(response -> response.body("name", equalTo(expectedName)));
    }

    @Step("Verify the new user job {0}")
    public void verifyNewUserJob(String expectedJob) {
        SerenityRest.restAssuredThat(response -> response.body("job", equalTo(expectedJob)));
    }

}

Now our steps are ready. Let’s refactor the main class with our tests:

package org.example.tests;

import net.serenitybdd.annotations.Steps;
import net.serenitybdd.annotations.Title;
import net.serenitybdd.junit.runners.SerenityRunner;
import org.example.steps.EmployeeSteps;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(SerenityRunner.class)
public class EmployeeTests {
    @Steps
    EmployeeSteps employeeSteps;

    @Test
    @Title("Get User")
    public void verifyValidUser() {
        employeeSteps.sendUser(2);
        employeeSteps.verifyStatusCode(200);
        employeeSteps.verifyId(2);
        employeeSteps.verifyFirstName("Janet");
        employeeSteps.verifyLastName("Weaver");
        employeeSteps.verifyEmail("janet.weaver@reqres.in");

    }

    @Test
    @Title("Create User")
    public void createValidUser() {

        employeeSteps.createUser();
        employeeSteps.verifyStatusCode(201);
        employeeSteps.verifyNewUserName("Test");
        employeeSteps.verifyNewUserJob("Test Architect");

    }

}

One more important thing we added is the @RunWith(SerenityRunner.class)” annotation on top of the class. As we have now organized our structure to meet some basic Serenity principles, we are ready to run the test using Serenity. This time (after we added the mentioned annotation) these tests will be run using the “SerenityRunner”. For that we can use exactly the same command to run our tests:

mvn clean verify

The output of the above program is

In the console, you should find printed messages for tests to start. At the same time under the target directory you can find the HTML-generated report we were talking about before:

You can open the report in any browser:

If you click on any test you should see a detailed description of the test steps:

One of the most important features of the Serenity and REST Assured integration is that by using detailed reporting, you can easily validate all requests and response details even if you are not adding any logs inside tests. Like the example above, for each executed REST request you can click the button “REST Query” and get a detailed request and response description:

There is another very useful Serenity Report – Serenity Symmary.html

As you can see, Serenity and REST Assured provide you with a wonderful combination. REST Assured keeps API testing clean and easy to maintain, while Serenity gives you outstanding test reporting and flexibility in running and grouping your tests inside a test suite.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Serenity BDD with Cucumber and Rest Assured

 

HOME

What is Serenity BDD?

Serenity BDD is an open-source library that aims to make the idea of living documentation a reality.

What is Rest Assured?

Rest Assured is one of the most powerful libraries for testing RESTful API using Java language. Rest-Assured is a Java-based library that is used to test RESTful Web Services. This library behaves like a headless Client to access REST web services. The Rest-Assured library also provides the ability to validate the HTTP Responses received from the server. For e.g. we can verify the Status code, Status message, Headers, and even the Body of the response. This makes Rest-Assured a very flexible library that can be used for testing. In this post, we will learn how to write high-quality, expressive REST API tests using Rest Assured and Serenity BDD.

Prerequisite

  1. Java 17 installed
  2. Maven installed
  3. Eclipse or IntelliJ installed

Dependency List:

  1. Java 17
  2. Maven – 3.9.5
  3. Serenity – 4.0.18
  4. Serenity Rest Assured – 4.0.18
  5. Serenity Cucumber – 4.0.18
  6. Rest Assured – 5.3.2
  7. JUnit – 4.13.2
  8. Maven Surefire Plugin – 3.2.1
  9. Maven Failsafe Plugin – 3.2.1
  10. Maven Compiler Plugin – 3.11.0

Project Structure

Step 1 – Update Properties section in Maven pom.xml

 <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <serenity.version>4.0.18</serenity.version>
        <serenity.cucumber.version>4.0.18</serenity.cucumber.version>
        <rest.assured.version>5.3.2</rest.assured.version>
        <junit.version>4.13.2</junit.version>
        <maven.compiler.plugin.version>3.11.0</maven.compiler.plugin.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <maven.surefire.plugin.version>3.2.1</maven.surefire.plugin.version>
        <maven.failsafe.plugin.version>3.2.1</maven.failsafe.plugin.version>
        <tags></tags>
    </properties>

Step 2 – Add dependencies to POM.xml

 <dependencies>

      <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-core</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-cucumber</artifactId>
        <version>${serenity.cucumber.version}</version>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>net.serenity-bdd</groupId>
        <artifactId>serenity-rest-assured</artifactId>
        <version>${serenity.version}</version>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>${rest.assured.version}</version>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
      </dependency>

    </dependencies>

Step 3 – Update the Build Section of pom.xml

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven.surefire.plugin.version}</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven.failsafe.plugin.version}</version>
                <configuration>
                    <includes>
                        <include>**/*.java</include>
                    </includes>
                    <parallel>methods</parallel>
                    <useUnlimitedThreads>true</useUnlimitedThreads>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>net.serenity-bdd</groupId>
                        <artifactId>serenity-single-page-report</artifactId>
                        <version>${serenity.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <tags>${tags}</tags>
                    <reports>single-page-html</reports>
                </configuration>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

<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>SerenityCucumberRestAssuredDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SerenityCucumberRestAssuredDemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <serenity.version>4.0.18</serenity.version>
        <serenity.cucumber.version>4.0.18</serenity.cucumber.version>
        <rest.assured.version>5.3.2</rest.assured.version>
        <junit.version>4.13.2</junit.version>
        <maven.compiler.plugin.version>3.11.0</maven.compiler.plugin.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <maven.surefire.plugin.version>3.2.1</maven.surefire.plugin.version>
        <maven.failsafe.plugin.version>3.2.1</maven.failsafe.plugin.version>
        <tags></tags>
    </properties>


    <dependencies>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber</artifactId>
            <version>${serenity.cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-rest-assured</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest.assured.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven.surefire.plugin.version}</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven.failsafe.plugin.version}</version>
                <configuration>
                    <includes>
                        <include>**/*.java</include>
                    </includes>
                    <parallel>methods</parallel>
                    <useUnlimitedThreads>true</useUnlimitedThreads>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>net.serenity-bdd</groupId>
                        <artifactId>serenity-single-page-report</artifactId>
                        <version>${serenity.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <tags>${tags}</tags>
                    <reports>single-page-html</reports>
                </configuration>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Step 4 – Create a Feature file in src/test/resources 

Create a features folder within src/test/resources to create test scenarios in the Feature file. Test Scenarios are created in a Feature File which contains an overall description of a feature as well as a number of scenarios. Feature files can be placed in different locations, but you can reduce the amount of configuration you need to do with serenity if you put them in the src/test/resources/features directory. In this feature file, will send a request, and the response should be of status “200” and employee name of “Tiger Nixon”. The feature file looks something like this:

Feature: Employee Details

  @GetEmployee
  Scenario: Get the details of employee
    Given I send a request to endpoint
    Then the API should return status 200
    And Response should contains employee name "Tiger Nixon"

Step 5 – Create the Step Definition class or Glue Code

To use Rest-assured, Serenity provides class SerenityRest

import net.serenitybdd.rest.SerenityRest;

 It is a Java method with an expression that is used to link it to Gherkin steps. When Cucumber executes a Gherkin step, it will look for a matching step definition to execute. These use annotations like @given, @when, and @then to match lines in the scenario to java methods

package org.example.definitions;

import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.restassured.response.Response;
import net.serenitybdd.rest.SerenityRest;
import static org.hamcrest.Matchers.equalTo;

public class EmployeeDefinitions {
    private static final String URL = "http://dummy.restapiexample.com/api/v1/employee/1";
    public Response response;

    @Given("I send a request to endpoint")
    public void sendRequest()  {

        response = SerenityRest.given().contentType("application/json").header("Content-Type", "application/json")
                .when().get(URL);
    }

    @Then("the API should return status {int}")
    public void verifyResponse(int status) {
        SerenityRest.restAssuredThat(response -> response.statusCode(status));
    }

    @And("Response should contains employee name {string}")
    public void verifyResponseContent(String expectedEmployeeName) {

        SerenityRest.restAssuredThat(response -> response.body("data.employee_name", equalTo(expectedEmployeeName)));
    }
}

Step 6 – Create Serenity Test Runner

Cucumber runs the feature files via JUnit and needs a dedicated Test Runner class to run the feature files. When you run the tests with serenity, you use the CucumberWithSerenity test runner. If the feature files are not in the same package as the test runner class, you also need to use the @CucumberOptions class to provide the root directory where the feature files can be found. It is the starting point for JUnit to start executing the tests. TestRunner class is created under src/test/java. The test runner to run all of the feature files looks like this:

import org.junit.runner.RunWith;

import io.cucumber.junit.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;

@RunWith(CucumberWithSerenity.class)
@CucumberOptions(plugin = { "pretty" }, features = "src/test/resources/features/Employee.feature", glue = {
		"org.example.definitions" })

public class SerenityAPITestRunner {

}

serenity.project.name = Rest API Testing using Serenity, Cucumber and JUnit4

Step 8 – Serenity Tests Execution

You can run the tests from SerenityAPITestRunner or from the command line by

mvn clean verify

Test Execution Page looks like this as shown below image

Step 9 – Verify the Serenity Reports

A number of reports are generated, but we are concerned about index.html and serenity-summary.html.

The report is well-formatted and contains consolidated results. Reporting is one of the major pillars of Serenity. Serenity Report not only reports on whether a test scenario passes or fails but documents what it did, in a step-by-step narrative format. The below pic illustrates the test results for our first acceptance criteria:

The test report generated by Serenity is placed under target/site/serenity/index.html. 

Index.html

The first tab is called “Overall Test Results” and it provides information about test statistics. This Overall Test Result shows the Scenario Results (No Of Test Cases Pass, No Of Test Cases Failed, No of Test Cases Pending, No Of Test Cases Ignored, No Of Test Cases Skipped). 

In the below pic, the report shows the test scenario steps status and time taken for each step to execute. 

With the use of the REST Query button, it’s possible to display query details. Visible details:

Path, Status code, Request Headers, Request Body, Request Cookies, Response Headers, Response Body.

There is also the “Requirements” tab. When we have tests as part of our code base, all test results will be organized as associated with requirements. 

There is also a “Features” tab. This page lists all the features that are part of your suite.  If you expand that row you’ll see the bit of narrative text that is part of the current feature file. 

Serenity-Summary.html

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Additional Tutorials:

Serenity BDD with Cucumber for Web Application
Serenity BDD with Cucumber for SpringBoot Application
How to manage screenshots in Serenity Report
Serenity Report for Web Application with Cucumber6 and Junit
 Integration of Serenity with Cucumber6 and JUnit5
Serenity BDD with Gradle and Cucumber for Web Application