API Automation with REST Assured, Cucumber and TestNG

HOME

Cucumber is not an API automation tool, but it works well with other API automation tools.

There are 2 most commonly used Automation Tools for JVM to test API – Rest-Assured and Karate. In this tutorial, I will use RestAssured with Cucumber and TestNG for API Testing.

What is Rest Assured?

REST Assured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs. REST Assured can be used easily in combination with existing unit testing frameworks, such as JUnit and TestNG. Rest assured, no matter how complex the JSON structures are, Rest Assured has methods to retrieve data from almost every part of the request and response.

What is Cucumber?

Cucumber is one such open-source tool, which supports Behaviour Driven Development(BDD). In simple words, Cucumber can be defined as a testing framework, driven by plain English. It serves as documentation, automated tests, and development aid – all in one.

Each scenario is a set of steps that the Cucumber must complete. Cucumber validates the software’s compliance with the specification and generates a report indicating success or failure for each scenario.

The cucumber must adhere to some basic syntax rules known as Gherkin to comprehend the scenarios.

In this tutorial, I will explain creating a framework for the testing of Rest API in Cucumber BDD.

Dependency List

  1. Cucumber – 7.18.0
  2. Java 17
  3. TestNG – 7.10.2
  4. Maven – 3.9.6
  5. Rest Assured – 5.4.0
  6. Maven Compiler – 3.13.0
  7. Maven Surefire – 3.2.5

Project Structure

Step 1 – Download and Install Java

Cucumber and Rest-Assured need Java to be installed on the system to run the tests. Click here to learn How to install Java.

Step 2 – Download and setup Eclipse IDE on the system

The Eclipse IDE (integrated development environment) provides strong support for Java developers. Click here to learn How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add several dependencies to the project. Click here to learn How to install Maven.

Step 4 – Create a new Maven Project

File -> New Project-> Maven-> Maven project-> Next -> Enter Group ID & Artifact ID -> Finish

Click here to learn How to create a Maven project

Step 5 – Install the Cucumber Eclipse plugin for the Eclipse project (Eclipse Only)

The Cucumber plugin is an Eclipse plugin that allows Eclipse to understand the Gherkin syntax. Cucumber Eclipse Plugin highlights the keywords present in the Feature File. To install Cucumber Eclipse Plugin, please refer to this tutorial – How to install Cucumber Eclipse Plugin.

Step 6 – Create source folder src/test/resources

A new Maven Project is created with 2 folders – src/main/java and src/test/java. To create test scenarios, we need a new source folder called – src/test/resources. To create this folder, right-click on your Maven project ->select New ->Java, and then Source Folder.

Mention the source folder name as src/test/resources and click the Next button. This will create a source folder under your new Maven project.

Step 7 – Add dependencies to the project

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <rest.assured.version>5.4.0</rest.assured.version>
    <cucumber.version>7.18.0</cucumber.version>
    <testng.version>7.10.2</testng.version>
    <maven.compiler.plugin.version>3.13.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.5</maven.surefire.plugin.version>
  </properties>

  <dependencies>

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

    <!-- Cucumber with TestNG -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-testng</artifactId>
      <version>${cucumber.version}</version>
    </dependency>

    <!-- Cucumber with Java -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>${cucumber.version}</version>
    </dependency>

    <!-- TestNG -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>${testng.version}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

Step 8 – Add Maven Compiler Plugin and Surefire Plugin

The compiler plugin is used to compile the source code of a Maven project. This plugin has two goals, which are already bound to specific phases of the default lifecycle:

  • compile – compile main source files
  • testCompile – compile test source files
 <build>
    <plugins>
      <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>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin.version}</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </build>

The complete POM.xml will look like something below:

<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>com.example</groupId>
  <artifactId>RestAPI_Cucumber_TestNG_Demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

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

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <rest.assured.version>5.4.0</rest.assured.version>
    <cucumber.version>7.18.0</cucumber.version>
    <testng.version>7.10.2</testng.version>
    <maven.compiler.plugin.version>3.13.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.5</maven.surefire.plugin.version>
  </properties>

  <dependencies>

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

    <!-- Cucumber with TestNG -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-testng</artifactId>
      <version>${cucumber.version}</version>
    </dependency>

    <!-- Cucumber with Java -->
    <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>${cucumber.version}</version>
    </dependency>

    <!-- TestNG -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>${testng.version}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <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>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin.version}</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Step 9 – Create a feature file under src/test/resources

Create a folder with name features. Now, create the feature file in this folder. The feature file should be saved with the extension .feature. This feature file contains the test scenarios created to test the application. The Test Scenarios are written in Gherkins language in the format of Given, When, Then, And, But.

Below is an example of a Test Scenario where we are using the GET method to get the information from the API.

Feature: Validation of get method

  @GetUserDetails
  Scenario Outline: Send a valid Request to get user details

    Given I send a request to the URL to get user details
    Then the response will return status <statusCode> and id <id> and email "<employee_email>" and first name "<employee_firstname>" and last name "<employee_lastname>"

    Examples:
    | statusCode | id  | employee_email          | employee_firstname | employee_lastname |
    | 200        | 2   | janet.weaver@reqres.in  | Janet              | Weaver            |

Step 10 – Create the Step Definition class or Glue Code

StepDefinition acts as an intermediate to your runner and feature file. It stores the mapping between each step of the scenario in the Feature file. So when you run the scenario, it will scan the step definition file to check the matched glue or test code.

package com.example.stepdefinitions;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class APIDemoDefinitions {

    private ValidatableResponse validatableResponse;
    private String endpoint = "https://reqres.in/api/users/2";

    @Given("I send a request to the URL to get user details")
    public void sendRequest(){
        validatableResponse = given().contentType(ContentType.JSON)
                .when().get(endpoint).then();

        System.out.println("Response :"+validatableResponse.extract().asPrettyString());
    }

    @Then("the response will return status {int} and id {int} and email {string} and first name {string} and last name {string}")
    public void verifyStatus(int expectedStatusCode, int expectedId, String expectedEmail, String expectedFirstName, String expectedLastName){

        validatableResponse.assertThat().statusCode(expectedStatusCode).body("data.id",equalTo(expectedId)).and()
                .body("data.email",equalTo(expectedEmail)).body("data.first_name",equalTo(expectedFirstName))
                .body("data.last_name",equalTo(expectedLastName));

    }
}

To use REST assured effectively it’s recommended to statically import methods from the following classes:

io.restassured.RestAssured.*
io.restassured.matcher.RestAssuredMatchers.*
org.hamcrest.Matchers.*

Step 11 – Create a TestNG Cucumber Runner class

A runner will help us run the feature file and act as an interlink between the feature file and the StepDefinition Class.

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(tags = "", features = {"src/test/resources/features"}, glue = {"com.example.stepdefinitions"},
        plugin = {})
public class CucumberRunnerTests extends AbstractTestNGCucumberTests {

}

Note:- The name of the Runner class should end with Test otherwise we can’t run the tests using Command-Line.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test  name="Rest Assured, Cucumber with TestNG Test">
        <classes>
            <class name="com.example.runner.CucumberRunnerTests"/>
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->

Step 13 – Run the tests from TestNG

You can execute the test script by right-clicking on TestRunner class -> Run As TestNG (Eclipse).

Step 16 – Run the tests from the Command Line

Run the below command in the command prompt to run the tests and to get the test execution report.

mvn clean test

Step 17 – Cucumber Report Generation

To get Cucumber Test Reports, add cucumber.properties under src/test/resources and add the below instruction in the file.

cucumber.publish.enabled=true

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

Generating and Using Access Tokens in a Rest API: A Complete Guide

HOME


public class AbstractHelper {
    
   String token;
   String accessToken;
   JsonPath jsonPath;

    public String generateToken() throws IOException {

        token = given().auth().preemptive()
                .basic(username, password)
                .contentType("application/x-www-form-urlencoded")
                .formParam("grant_type", "client_credentials")
                .when().post("https://example.com/accesstoken").asString();

        System.out.println("Token :" + token);

        jsonPath = new JsonPath(token);
        accessToken = jsonPath.getString("access_token");
        System.out.println("Access Token :" + accessToken);
        return accessToken;
    }

}

JsonPath jsonPath = new JsonPath(token);
accessToken = jsonPath.getString("access_token");
import java.io.IOException;

public class AccessToken_Example extends AbstractHelper {

    Response response;
    
   @Test
    public void testRequest() throws IOException {

        response = RestAssured.given()
                .auth().oauth2(generateToken()).when().get("https://localhost/8080/coreid").then()
                .extract()
                .response();

        System.out.println("Response :" + response.asString());
        int statusCode = response.getStatusCode();

        Assert.assertEquals(200,statusCode);
    }
}

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();
        }

    }
}

Deserialization – How to create JSON Object to JAVA Object Using Gson API

HOME

In this tutorial, I will explain the conversion of JSON Object (payload) to JAVA Object. We will use Gson API for the same purpose.

Before going through this tutorial, spend some time understanding Serialization using Gson API.

We can parse the JSON or XML response into POJO classes. After parsing into POJO classes, we can easily get values from the response easily. This is called De-serialization. For this, we can use any JSON parser APIs. Here, we are going to use Gson API.

To start with, add the below dependency to the project.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Sample JSON Payload

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

Let us create a class called Employee with a field name exactly (case-sensitive) the same as node names in the above JSON string because with the default setting while parsing JSON object to Java object, it will look on getter setter methods of field names. 

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;
	}

}

Gson class provides multiple overloaded fromJson() methods to achieve this. Below is a list of available methods:-

In the below test, I have mentioned the JSON Payload string in the test and used Gson API to deserialize the JSON payload to JAVA Object.

   @Test
	public void getDetailFromJson() {
		
		// De-serializing from JSON String
		String jsonString = "{\r\n" + "  \"firstName\": \"Tom\",\r\n" + "  \"lastName\": \"John\",\r\n"
				+ "  \"age\": 30,\r\n" + "  \"salary\": 50000.0,\r\n" + "  \"designation\": \"Lead\",\r\n"
				+ "  \"contactNumber\": \"+917642218922\",\r\n" + "  \"emailId\": \"abc@test.com\"\r\n" + "}";

		Gson gson = new Gson();
		// Pass JSON string and the POJO class
		Employee employee = gson.fromJson(jsonString, Employee.class);

		// Now use getter method to retrieve values
		System.out.println("Details of Employee is as below:-");
		System.out.println("First Name : " + employee.getFirstName());
		System.out.println("Last Name : " + employee.getLastName());
		System.out.println("Age : " + employee.getAge());
		System.out.println("Salary : " + employee.getSalary());
		System.out.println("designation : " + employee.getDesignation());
		System.out.println("contactNumber : " + employee.getContactNumber());
		System.out.println("emailId : " + employee.getEmailId());
		System.out.println("########################################################");

	}

The output of the above program is

We can get the JSON payload from a file present in a project under src/test/resources as shown in the below image.

public class EmployeeDeserializationGsonTest {

	@Test
	public void fromFile() throws FileNotFoundException {

		Gson gson = new Gson();
		// De-serializing from a json file
		String userDir = System.getProperty("user.dir");
		File inputJsonFile = new File(userDir + "\\src\\test\\resources\\EmployeePayloadUsingGson.json");
		FileReader fileReader = new FileReader(inputJsonFile);
		Employee employee1 = gson.fromJson(fileReader, Employee.class);

		// Now use getter method to retrieve values
		System.out.println("Details of Employee is as below:-");
		System.out.println("First Name : " + employee1.getFirstName());
		System.out.println("Last Name : " + employee1.getLastName());
		System.out.println("Age : " + employee1.getAge());
		System.out.println("Salary : " + employee1.getSalary());
		System.out.println("designation : " + employee1.getDesignation());
		System.out.println("contactNumber : " + employee1.getContactNumber());
		System.out.println("emailId : " + employee1.getEmailId());
		System.out.println("########################################################");
	}
}

The output of the above program is

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

UnMarshalling- How to convert XML to Java Objects using JAXB

HOME

This tutorial explains how to use JAXB (Java Architecture for XML Binding) to convert an XML document to Java Objects.

The previous tutorial has explained the conversion of Java Objects to XML.

As of Java 11, JAXB is not part of the JRE anymore, and you need to configure the relevant libraries via your dependency management system, for example, either Maven or Gradle.

Configure the Java compiler level to be at least 11 and add the JAXB dependencies to your pom file.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>org.example</groupId>
  <artifactId>JAXBDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
 
  <name>JAXBDemo</name>
  <url>http://www.example.com</url>
 
  <properties>  
 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
  </dependency>
     
 <dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.3</version>
   </dependency>
 </dependencies>
    
</project>

Sample XML Structure

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EmployeeDetails>
    <firstName>Terry</firstName>
    <lastName>Mathew</lastName>
    <gender>female</gender>
    <age>30</age>
    <maritalStatus>married</maritalStatus>
    <designation>Manager</designation>
    <contactNumber>+919999988822</contactNumber>
    <emailId>abc@test.com</emailId>
    <GrossSalary>75000.0</GrossSalary>
</EmployeeDetails>

Un-marshalling provides a client application the ability to convert XML data into JAXB-derived Java objects.

Let’s see the steps to convert XML document into java object.

  1. Create POJO Class
  2. Create the JAXBContext object
  3. Create the Unmarshaller objects
  4. Call the unmarshal method
  5. Use getter methods of POJO to access the data

Now, let us create the Java Objects (POJO) for the above XML.

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "EmployeeDetails")
@XmlAccessorType(XmlAccessType.FIELD)

//Define the order in which the fields are written in XML
@XmlType(propOrder = { "firstName", "lastName", "gender", "age", "maritalStatus", "designation", "contactNumber","emailId", "salary" })

public class Employee {

	private String firstName;
	private String lastName;
	private int age;

	@XmlElement(name = "GrossSalary")
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;
	private String gender;
	private String maritalStatus;

	public Employee() {
		super();

	}

	// 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;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getMaritalStatus() {
		return maritalStatus;
	}

	public void setMaritalStatus(String maritalStatus) {
		this.maritalStatus = maritalStatus;
	}

	@Override
	public String toString() {
		return "Employee [FirstName=" + firstName + ", LastName=" + lastName + ", Age=" + age + ", Salary=" + salary
				+ ", Designation=" + designation + ", ContactNumber=" + contactNumber + ", EmailId=" + emailId
				+ ", Gender=" + gender + ", MaritalStatus=" + maritalStatus + "]";
	}
}

Create the following test program for reading the XML file. The XML file is present under src/test/resources.

Let’s use JAXB Unmarshaller to unmarshal our JAXB_XML back to a Java object:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.junit.Test;

public class JAXBDeserialization {
	
	@Test
	public void JAXBUnmarshalTest() {

		try {

			String userDir = System.getProperty("user.dir");
			File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file);

			System.out.println("FirstName: " + employee.getFirstName());
			System.out.println("LastName: " + employee.getLastName());
			System.out.println("Age: " + employee.getAge());
			System.out.println("Salary: " + employee.getSalary());
			System.out.println("Contact Number: " + employee.getContactNumber());
			System.out.println("Designation: " + employee.getDesignation());
			System.out.println("Gender: " + employee.getGender());
			System.out.println("EmailId: " + employee.getEmailId());
			System.out.println("MaritalStatus: " + employee.getMaritalStatus());

		} catch (JAXBException e) {
			e.printStackTrace();
		}

	}

	}

When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:

The output of the above program is

There is another simple way of unmarshalling the XML to Java Objects.

    @Test
	public void JAXBUnmarshalTest1() {

		try {

			String userDir = System.getProperty("user.dir");
			File file = new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml");

			JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Employee emp = (Employee) jaxbUnmarshaller.unmarshal(file);

			System.out.println(emp);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:

The output of the above program is

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

Setup Basic REST Assured Maven Project In Eclipse IDE

HOME

In the previous tutorial, I provided the Introduction of Rest Assured. In this tutorial, I will explain how to set up a basic Rest Assured Maven project in Eclipse IDE. Before starting, let us recap about Rest Assured.

What is Rest Assured?

REST Assured is a Java DSL for simplifying testing of REST-based services built on top of HTTP Builder. It supports POST, GET, PUT, DELETE, OPTIONS, PATCH and HEAD requests and can be used to validate and verify the response of these requests.

The Rest-Assured library also provides the ability to validate the HTTP Responses received from the server. 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.

What is Maven?

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.

Step 1- Download and Install Java

Rest-Assured needs Java to be installed on the system to run the tests. Click here to learn How to install Java.

Step 2 – Download and setup Eclipse IDE on the system

The Eclipse IDE (integrated development environment) provides strong support for Java developers. Click here to learn How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add several dependencies to the project. Click here to learn How to install Maven.

Step 4 – Create a new Maven Project

File -> New Project-> Maven-> Maven project ->Next

Step 4.1 – Select “Create a simple project”. Click on the Next Button.

Step 4.2 – Provide Group Id and Artifact Id and click on the finish button.

Group Id – com.example
Artifact Id – restassured_demo

Step 4.3Below is the structure of the Maven project in Eclipse.

Step 4.4 – This is the structure of POM.xml created for the project.

Step 5 – Add Rest-Assured, and JUnit dependencies to the project.

<dependencies>
  
<!-- Junit4 Dependency -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
  
<!-- Rest Assured Dependency -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.3.3</version>
    <scope>test</scope>
</dependency>

</dependencies>

Step 6 – Below are the Rest Assured, and junit jar files present under Maven Dependencies.

Point to Remember

1. Don’t add the dependency on Hamcrest explicitly. Rest Assured includes it by default. You can see it in the Maven Dependencies folder under the project. 

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.

How to pass authorization token in header in Rest assured?

HOME

 <dependencies>

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

        <!-- TestNG Dependency-->
      <dependency>
          <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.8.0</version>
         <scope>test</scope>
       </dependency>

</dependencies>

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;

public class BasicAuth_Demo {


    @Test
    public void createUser() {
        Response response = given()
                .auth()
                .preemptive()
                .header("Authorization", "Token")
                .header("Accept", "application/json")
                .contentType(ContentType.JSON)
                .body(validRequest)
                .when()
                .post("http://localhost:8080/users")
                .then()
                .extract()
                .response();

        int statusCode = response.getStatusCode();

        Assert.assertEquals(statusCode,200);
    }
}

package org.example;

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.Before;
import org.junit.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class BasicAuth_Demo {

    private static final String BASE_URL = "https://httpbin.org/basic-auth/user/pass";
    private static final String TOKEN = "Basic dXNlcjpwYXNz";

    @Before
    public void setup() {
        given().baseUri(BASE_URL);
    }

    @Test
    public void validateToken() {


        Response response = given()
                .header("Accept", "application/json")
                .header("Authorization",TOKEN)
                .contentType(ContentType.JSON)
                .when()
                .get("https://httpbin.org/basic-auth/user/pass")
                .then()
                .log().all()
                .extract()
                .response();

        assertThat(response.getStatusCode(),equalTo(200));

    }

}