Tags in Cucumber

HOME

In this tutorial, I will explain Tags in Cucumber.

What are Tags?

Tags are a great way to organize Features and Scenarios.
By default, Cucumber executes all the scenarios present in a Feature File. If you want to run a specific scenario from the feature file, then a tag can be used. It allow flexible execution of scenarios or features based on specific tags.

Tags can be declared as below:-

 @TagName
   Scenario: Test the scenario

Here,

@: It is a symbol used to declare a tag.
TagName: It is the name of a specific test.

In the below example, there are 2 feature files – LoginPage.feature and DashboardPage.feature. LoginPage.feature contains 4 different scenarios with different tags, whereas DashboardPage.feature contains 3 different scenarios.

Feature: Login to HRM Application

  Background:
    Given User is on Login page

  @ValidCredentials
  Scenario: Login with valid credentials

    When User enters username as "Admin"
    And User enters password as "admin123"
    Then User should be able to login successfully

  @InValidCredentials
  Scenario: Login with invalid credentials

    When User enters username as "Admin123"
    And User enters password as "admin123"
    Then User should see an error message "Invalid credentials"

  @InValidCredentials
  Scenario: Login with invalid username and valid password

    When User enters username as "1234"
    And User enters password as "admin123"
    Then User should see an error message "Invalid credentials"

  @InValidCredentials @SpecialCharacters
  Scenario: Login with special characters

    When User enters username as "$$$$"
    And User enters password as "%%%%%"
    Then User should see an error message "Invalid credentials"

Feature: Dashboard page validation

  Background:
    Given User is on Login page
    When User enters username as "Admin"
    And User enters password as "admin123"
    Then User should be able to login successfully

  @ValidQuickLaunch
  Scenario Outline: Login with valid credentials to check QuickLanuch options

    Then there are valid QuickLaunch options '<options>'

    Examples:
      | options                  |
      | Assign Leave             |
      | Leave List               |
      | Timesheets               |

Running a single Cucumber Tag

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features= {"src/test/resources/features"}, 
        glue= {"org.example.definitions"},
        tags = ("@ValidCredentials"))

public class RunCucumberTest {
}

Tags can be placed above Feature, Scenario, Scenario Outline, and Examples.

A feature or Scenario can have as many tags. However, each tag should be separated by a blank space.

How to execute Cucumber Tag that runs multiple scenarios

Let us consider a situation where a tag (@InValidCredentials) has multiple test scenarios, and you use this tag in the Runner class, then all the test scenarios associated with this tag will execute.

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features= {"src/test/resources/features"}, 
            glue= {"org.example.definitions"},
            tags = ("@InValidCredentials"))

public class RunCucumberTest {
}

The testing through multiple tags can be done by using two operators:

  1. OR operator
  2. AND operator

OR operator

OR means scenarios that are tagged either with @BlankCredentials or @InvalidCredentials will execute. The syntax is mentioned below:

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features= {"src/test/resources/features"}, 
             glue= {"org.example.definitions"},
             tags = ("@ValidCredentials or @SpecialCharacters"))

public class RunCucumberTest {
}

AND operator

Suppose you want to test an application with multiple test cases and if the first test case is failed in the application, we do not want to test the second test case. The syntax is mentioned below:

@CucumberOptions(features = { "src/test/resources/features/CucumberTagsExample.feature" }, 
        glue = {"com.cucumber.demo.definitions" }, 
        tags = ("@BlankCredentials and @InValidCredentials"))

How to ignore Tags in Cucumber?

To skip a specific test scenario, use not keyword.

@CucumberOptions(features= {"src/test/resources/features/LoginPage.feature"}, 
               glue= {"org.example.definitions"}, 
               tags = ("not @InValidCredentials"))

All these syntaxes are valid for Cucumber Version – 6.8.1

The below-mentioned syntax is not valid for Cucumber Version – 6.8.1 and above

AND - {"@BlankCredentials , @InValidCredentials"}
OR - {"@BlankCredentials" , "@InValidCredentials"}
NOT - {"~@InValidCredentials"}

@CucumberOptions(features= {"src/test/resources/features/LoginPage.feature","src/test/resources/features/DashboardPage.feature"}, 
glue= {"org.example.definitions"})

Cucumber – What is Feature File in Cucumber
Step Definition in Cucumber
Cucumber – JUnit Test Runner Class
Background in Cucumber
Conditional Hooks in Cucumber

Assertion of JSON in Rest Assured using Hamcrest

Last Updated On

HOME

In this tutorial, we will discuss various types of Assertions present in Hamcrest that are used in Rest Assured.

Table Of Contents

What is Assertion?

An assertion is a way to verify that the expected result and the actual result match or not in the test case.  A test is considered successful ONLY if it is completed without throwing any exceptions. If the current value and the expected value match then the assertion passes and when the assertion passes nothing happens. But when an assertion fails, it will fail the test case.

There are various ways to perform assertions in API Testing. For API Testing, we are using Rest Assured, which uses either Hamcrest or JUnit assertions. We are going to discuss Hamcrest Assertions here.

What is Hamcrest?

Hamcrest is a framework for writing matcher objects, allowing ‘match’ rules to be defined declaratively. We do not need to add Hamcrest dependency explicitly as the Rest-Assured 4.3.3 version includes itself. To learn more about Hamcrest, please refer to this link.

We need to add the below dependency to use Hamcrest in the project. Please use the latest version from here

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>3.0</version>
    <scope>test</scope>
</dependency>

To run all the scenarios mentioned below, please add the below-mentioned dependencies to the POM.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>RestAssured_TestNG_Demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <hamcrest.version>3.0</hamcrest.version>
        <testng.version>7.8.0</testng.version>
        <rest-assured.version>5.3.2</rest-assured.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

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

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

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

    </dependencies>
</project>

Below is an example of a JSON Response. I will perform various assertions on this JSON Response.

To use hamcrest assertion, please import the Matchers class, static member.

  1. equalTo – It checks whether the retrieved number from the response is equal to the expected number.
  2. greaterThan – checks extracted number is greater than the expected number.
  3. greaterThanOrEqualTo – checks whether the extracted number is greater than equal to the expected number.
  4. lessThan – It checks whether the retrieved number from the response is lesser than the expected number.
  5. lessThanOrEqualTo – It checks whether the retrieved number from the response is lesser than or equal to the expected number.

Below assertions are imported from the package shown below:-

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;

Below are examples to show the use of number-related assertions.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;

public class HamcrestNumberExample {

    public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

    @Test
    public void numberAssertions() {
        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint).then()
                .body("totalprice", equalTo(164));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("totalprice",greaterThan(100));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("totalprice",greaterThanOrEqualTo(50));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("totalprice",lessThan(1000));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("totalprice",lessThanOrEqualTo(1000));

    }

}

The output of the above program is

  1. equalTo – It checks whether the extracted string from JSON is equal to the expected string.
  2. equalToIgnoringCaseIt checks if the extracted string from JSON matches the expected string. The comparison does not consider case (small or capital).
  3. equalToIgnoringWhiteSpace – It checks if the extracted string from JSON matches the expected string. It takes into account the white spaces.
  4. containsString – It checks whether the extracted string from JSON contains the expected string as a substring.
  5. startsWith It checks whether the extracted string from JSON is starting with a given string or character.
  6. endsWithIt checks whether the extracted string from JSON is ending with a given string or character.

Below assertions are imported from the package shown below:-

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;

Below are examples to show the use of string-related assertions.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;

public class HamcrestStringAssertions {

    public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

    @Test
    public void stringAssertions() {
        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("firstname",equalTo("Mary"));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("firstname",equalToIgnoringCase("mary"));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("firstname",containsString("Mary"));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("firstname",startsWith("M"));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("firstname",endsWith("y"));

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("firstname",equalToIgnoringWhiteSpace("   Mary "));


    }
}

The output of the above program is

nullValue

It checks whether the extracted response from JSON is NULL or Not.

Below assertions are imported from the package shown below:-

import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

Below are examples to show the use of collection-related assertions.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

public class HamcrestNullAssertion {
    
   public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

    @Test
    public void nullAssertion() {
        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("totalprice1", is(nullValue()));
    }
}

The output of the above program is

hasKey

It checks whether the extracted map has an expected key.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.hasKey;

public class HamcrestHasKeyAssertion {
    
    public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

    @Test
    public void collectionAssertions() {

        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("bookingdates",hasKey("checkin"));

    }
}

The output of the above program is

Not Assertion

The not assertion inverts the meaning of the other assertions. For example, if you want to perform negative assertions, then we can use any assertions with NOT.

The below assertion is imported from the package shown below:-

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;

Below are examples to show the use of negative assertions.

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;

public class HamcrestNotAssertion {
    
    public String endpoint = "https://restful-booker.herokuapp.com/booking/1";

    @Test
    public void negativeAssertions() {
        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint)
                .then().body("totalprice",not(equalTo(874)));

    }
}

The output of the above program is

Multiple Assert Statements

In the below example, all 3 assertions will fail. It will only execute the first assertion. If the first assertion fails, then other assertions will not be executed.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.equalTo;

public class HamcrestMultipleAssertions {

    public String endpoint = "https://restful-booker.herokuapp.com/booking/1";
    
    @Test
    public void test1() {
        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint).then()
                .body("firstname", equalTo("Jim"), // will fail
                        "lastname", equalTo("Smith"), // will fail
                        "totalprice", equalTo(314)); // will fail
    }

}

The output of the above program is

To execute all the assertions in the test case, combine them into a single body. This should be done just like it is shown below. You can see that all the assertions failed, and they are shown in the response.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.equalTo;

public class HamcrestMultipleAssertions {

    public String endpoint = "https://restful-booker.herokuapp.com/booking/1";
    
    @Test
    public void test1() {
        RestAssured.given().contentType(ContentType.JSON)
                .when().get(endpoint).then()
                .body("firstname", equalTo("Jim"), // will fail
                        "lastname", equalTo("Smith"), // will fail
                        "totalprice", equalTo(314)); // will fail
    }

}

The output of the above program is

I have tried to show the use of a few of the most commonly used assertion methods. There are many more methods available in Hamcrest package. To know about other methods, write import static org.hamcrest.Matchers and add (.) at the end, it will show the list of all the methods available in Hamcrest.

To know more details related to Hamcrest assertion, you can refer the official website – Hamcrest

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

How to test POST JSON Object request using Java Map in Rest Assured
How to create JSON Array Request Body
Extraction from JSON in Rest Assured
How To Send A JSON/XML File As Payload To Request using Rest Assured
Logging in Rest Assured

How to Parameterize tests in JUnit4

HOME

JUnit 4 has a feature called parameterized tests. Parameterized test means to execute the test multiple times with different sets of test data. This eliminates the redundancy of the code. This helps the developers to save time by eliminating the need to copy the code multiple times. Parameterizing tests can increase code coverage and provide confidence that the code is working as expected. These are the steps that need to be followed to create a parameterized test.

  • Annotate test class with @RunWith(Parameterized.class).
  • Create an instance variable for each “column” of test data.
  • It has a single constructor that contains the test data.
  • Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.
  • Create your test case(s) using the instance variables as the source of the test data.

In a Maven project, to parameterize the tests in JUnit4, we need to add a dependency to POM.xml.

 <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <version>5.8.2</version>
      <scope>test</scope>
</dependency>

The test case will be invoked once for each row of data.

There are multiple ways to parameterize a test. They are the following:

  1. Parameterized Test with Constructor
  2. Parameterized Test with Parameter Annotation
  3. Parameterized Test using CSV File

Let us see parameterized tests in action.

1. Parameterized Test with Constructor

Steps to create a Parameterized JUnit test

1. Create a parameterized test class

Annotate your test class using @runWith(Parameterized.class).

Declaring the variable ‘num1’, ‘num2’, ‘num3’ as private and type as int.

@RunWith(value = Parameterized.class)
public class ParameterizedTest {

    private int num1;
    private int num2;
    private int num3;

2. Create a constructor

    public ParameterizedTest(int num1, int num2, int num3) {
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }

3. Create a static method that generates and returns test data.

Creating a two-dimensional array (providing input parameters for multiplication). Using the asList method, we convert the data into a List type. Since the return type of method input is the collection.

Using @Parameters annotation to create a set of input data to run our test.

    @Parameterized.Parameters(name = "{index}: multiply({0}*{1}) = {2}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {1, 1, 1},
                {2, 2, 4},
                {8, 2, 16},
                {4, 5, 20},
                {5, 5, 25}
        });
    }

The static method identified by @Parameters annotation returns a Collection, where each entry in the Collection will be the input data for one iteration of the test.

The complete code is shown below:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;

@RunWith(value = Parameterized.class)
public class ParameterizedTest {

    private int num1;
    private int num2;
    private int num3;

    public ParameterizedTest(int num1, int num2, int num3) {
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }

    @Parameterized.Parameters(name = "{index}: multiply({0}*{1}) = {2}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {1, 1, 1},
                {2, 2, 4},
                {8, 2, 16},
                {4, 5, 20},
                {5, 5, 25}
        });
    }

    @Test
    public void multiplication() {
        System.out.println("The product of "+num1+" and "+num2+" is "+num3);
        assertEquals((num1*num2), num3);
    }
}

The output of the above program is

2. Parameterized Test with Parameter Annotation

It is also possible to inject data values directly into fields without needing a constructor using the @Parameter annotation.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;

@RunWith(value = Parameterized.class)
public class ParameterizedTest1 {

    @Parameterized.Parameter(value = 0)
    public int num1;

    @Parameterized.Parameter(value = 1)
    public int num2;

    @Parameterized.Parameter(value = 2)
    public int num3;

    @Parameterized.Parameters(name = "{index}: multiply({0}*{1}) = {2}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {1, 1, 1},
                {2, 2, 4},
                {8, 2, 16},
                {4, 5, 20},
                {5, 5, 24}
        });
    }

    @Test
    public void multiplication() {
        System.out.println("The product of "+num1+" and "+num2+" is "+num3);
        assertEquals((num1*num2), num3);
    }
}

The output of the above program is

3. Parameterized Test using CSV File

We can use an external CSV file to load the test data. This helps if the number of possible test cases is quite significant, or if test cases are frequently changed. The changes can be done without affecting the test code.

To start with, add a JUnitParams dependency to POM.xml

<dependency>
     <groupId>pl.pragmatists</groupId>
     <artifactId>JUnitParams</artifactId>
     <version>1.1.1</version>
     <scope>test</scope>
</dependency>

Let’s say that we have a CSV file with test parameters as JunitParamsTestParameters.csv:

Now let’s look at how this file can be used to load test parameters in the test method:

import junitparams.JUnitParamsRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import junitparams.FileParameters;
import static org.junit.Assert.assertEquals;

@RunWith(JUnitParamsRunner.class)
public class ParameterizedTest2 {

    @Test
    @FileParameters("src/test/resources/JunitParamsTestParameters.csv")
    public void multiplication(int num1, int num2, int num3) {
        System.out.println("The product of "+num1+" and "+num2+" is "+num3);
        assertEquals((num1*num2), num3);
    }
}

The output of the above program is

The parameterized test enables us to execute the same test over and over again using different values.

Important annotations to be used during parameterization

  • @RunWith
  • @Parameters

Congratulations. We are done. I hope this tutorial is helpful to you. Happy Learning!!

JUnit4 Assertions
How to generate JUnit4 Report
Integration of Cucumber with Selenium and JUnit
Integration of Serenity with Cucumber6 and JUnit5
Integration of Serenity with JUnit4
Rest API Test in Cucumber BDD

How to pass Parameters in TestNG

 HOME

@Parameters("value")

Let us explain how we can use parameters. To start with, add the below dependencies to the POM.xml in the case of the Maven project.

 <properties>
        <selenium.version>4.14.0</selenium.version>
        <testng.version>7.8.0</testng.version>
        <webdrivermanager.version>5.5.3</webdrivermanager.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
 </properties>

 <dependencies>

    <!-- Selenium -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>${selenium.version}</version>
    </dependency>

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

    <!-- Web Driver Manager -->
    <dependency>
        <groupId>io.github.bonigarcia</groupId>
        <artifactId>webdrivermanager</artifactId>
        <version>${webdrivermanager.version}</version>
    </dependency>

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

 </dependencies>

Implementation Steps

Step 1 – Create a JAVA test class, say, TestNGParameterizationDemo.java

Step 2 – Add test method parameterizedTest() to the test class. This method takes a string as an input parameter

Add the annotation @Parameters(“browser”) to this method. The parameter passes a value from testng.xml

Step 3 – Create a TestNG.xml and pass the value of the parameter in this configuration file.

Below is an example that shows the use of Parameters.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import java.util.concurrent.TimeUnit;

import static org.testng.Assert.assertEquals;

public class TestNGParameterizationDemo {
    WebDriver driver;
    By userName = By.name("username");
    By passWord = By.name("password");

    By loginBtn = By.xpath("//*[@class='oxd-form']/div[3]/button");

    By loginTitle = By.xpath("//*[@class='oxd-topbar-header-breadcrumb']/h6");

    By errorMessage = By.xpath("//*[@class='orangehrm-login-error']/div[1]/div/p");


    @BeforeMethod
    @Parameters("browser")
    public void parameterizedTest(String browser) {
        if (browser.equalsIgnoreCase("firefox")) {

            WebDriverManager.firefoxdriver().setup();
            FirefoxOptions options=new FirefoxOptions();
            options.addArguments("--start-maximized");
            driver=new FirefoxDriver(options);
            System.out.println("Browser Started :" + browser);

        } else if (browser.equalsIgnoreCase("chrome")) {
            WebDriverManager.chromedriver().setup();
            ChromeOptions options=new ChromeOptions();
            options.addArguments("--start-maximized");
            driver=new ChromeDriver(options);
            System.out.println("Browser Started :" + browser);
        }

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://opensource-demo.orangehrmlive.com/");

    }

    @Test
    public void validCredentials()  {

        driver.findElement(userName).sendKeys("Admin");
        driver.findElement(passWord).sendKeys("admin123");
        driver.findElement(loginBtn).click();
        String newPageText = driver.findElement(loginTitle).getText();
        System.out.println("newPageText :" + newPageText);
        assertEquals(newPageText,"Dashboard");
    }

    @Test
    public void invalidCredentials() {

        driver.findElement(userName).sendKeys("1234");
        driver.findElement(passWord).sendKeys("admin3456");
        driver.findElement(loginBtn).click();
        String actualErrorMessage = driver.findElement(errorMessage).getText();
        System.out.println("Actual ErrorMessage :" + actualErrorMessage);
        assertEquals(actualErrorMessage,"Invalid credentials");

    }

    @AfterMethod
    public  void closeBrowser() {
        driver.quit();
    }
}

TestNG.xml looks like this, as shown below. Here, the parameter name is the browser name value for the browser is “Chrome”. So, this “Chrome” value is passed to Test as a parameter, and as a result, a Google Chrome browser opens. Similarly, the same tests are run using Firefox, as it is mentioned in the testng.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">

<suite name="Suite ">

    <test name="Chrome Test">
        <parameter name="browser" value="chrome" />
        <classes>
            <class name="TestNGParameterizationDemo" />
        </classes>
    </test> <!-- Test -->

    <test name="Firefox Test">
        <parameter name="browser" value="firefox" />
        <classes>
            <class name="TestNGParameterizationDemo" />
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->

The output of the above program is

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to test POST Request using Rest Assured

HOME

In the last tutorial, I explained How to test GET Request using Rest Assured. In this tutorial, I will automate a POST Request using Rest Assured. I will verify the status code, line of Status, and content of the Response. To set up a basic Rest Assured Maven Project, click here and Gradle project, click here.

Add the below-mentioned dependencies to the pom.xml. The latest dependency can be downloaded from here.

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
</dependency>
 
<dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>5.5.1</version>
      <scope>test</scope>
</dependency>

What is the POST Method?

An HTTP POST method is used to create a new resource in the collection of resources. The request body is passed as a JSON/XML or in a different format. If a resource is created successfully by the endpoint or server, it returns a status code 201(Created). It also provides a Location header with a link to the newly-created resource with the 201 HTTP status. It may return 200 (OK) and 204 (No Content) status code as well, based on how the API is developed.

POST is neither safe nor idempotent. It is therefore recommended for non-idempotent resource requests. Making two identical POST requests will most result in two resources containing the same information.

Below are the steps to test a POST Request using Rest Assured:

Step 1 Specify the base URL to the RESTful web service using the RestAssured class.

RestAssured.baseURI = "https://dummy.restapiexample.com/api/v1/create";

Step 2  Every Request in the Rest-Assured library is represented by an interface called RequestSpecification. This interface allows modifying the request, like adding headers or adding authentication details. Use the RestAssured class to generate a RequestSpecification.

requestSpecification = RestAssured.given();

RequestSpecification is imported from package:

import io.restassured.specification.RequestSpecification;

Step 3 – Set the content type. This step specifies the format in which the request payload will be sent to the server. Here, the Content-Type is JSON.

requestSpecification.contentType(ContentType.JSON);

contentType is imported from restassured.http package:

import io.restassured.http.ContentType;

Step 4 Pass Request Body as String.

requestSpecification.body(jsonString);

Step 5 – Send the POST request to the server. Then receive the response of the request made by REST Assured. This response contains every detail returned by hitting request i.e. response body, response headers, status code, status lines, cookies, etc. The response is imported from package:

import io.restassured.response.Response;

Step 6 To validate a response like status code or value, we need to get the reference of type ValidatableResponse

ValidatableResponse is an interface. A validatable response to a request made by, REST Assured. ValidatableResponse is imported from package:

import io.restassured.response.ValidatableResponse;

PrettyPrint() – It prints the response body if possible and returns it as a string. Pretty printing is possible for content-types JSON, XML, and HTML.

Below is the example of testing a POST request in Non-BDD format. I have used ValidatableResponse for the assertion of status. It is also used for the status line and body of the Response.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;

public class POST_NonBDDDemo {

    RequestSpecification requestSpecification;
    Response response;
    ValidatableResponse validatableResponse;

    @Test
    public void verifyStatusCode() {

        String jsonString = "{\"name\":\"newapitest\",\"salary\":\"4000\",\"age\":\"29\"}";

        RestAssured.baseURI = "https://dummy.restapiexample.com/api/v1/create";

        // Create a request specification
        requestSpecification = RestAssured.given();

        // Setting content type to specify format in which request payload will be sent.
        requestSpecification.contentType(ContentType.JSON);

        // Adding body as string
        requestSpecification.body(jsonString);

        // Calling POST method
        response = requestSpecification.post();

        // Let's print response body.
        String responseString = response.prettyPrint();

        /*
         * To perform validation on response, we need to get ValidatableResponse type of
         * response
         */
        validatableResponse = response.then();

        // Check status code
        validatableResponse.statusCode(200);

        // It will check if status line is as expected
        validatableResponse.statusLine("HTTP/1.1 200 OK");

        // Check response body - name attribute
        validatableResponse.body("data.name", equalTo("newapitest"));

        // Check response body - message attribute
        validatableResponse.body("message", equalTo("Successfully! Record has been added."));

    }
}

The below image shows the test result of the above test.

Test implemented in BDD Format

import static org.hamcrest.Matchers.equalTo;

2. given is a static import from package:

import static io.restassured.RestAssured.given;

Below is an example of a BDD Test.

import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;

public class POST_BDDDemo {
    
    ValidatableResponse validatableResponse;

    @Test
    public void createUser() {

        String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";

        // GIVEN
        validatableResponse = given()
                .baseUri("https://dummy.restapiexample.com/api")
                .contentType(ContentType.JSON)
                .body(json)

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

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

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

}

The below image shows the test result of the above test.

String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";

.baseUri("https://dummy.restapiexample.com/api")
.contentType(ContentType.JSON)
.body(json)

".assertThat().statusCode(200)"
.body("data.name", equalTo("apitest"))
.body("message", equalTo("Successfully! Record has been added."))

The above tests can be used in both Maven and Gradle projects.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to test GET Request using Rest Assured

HOME

In the last tutorial, I explained the Setup of the REST Assured Maven Project In Eclipse IDE. In this tutorial, I will automate a GET Request. I will verify the status code, line of Status, and content of the Response.

RestAssured is a class that consists of many static fields and methods. It supports POST, GET, PUT, DELETE, HEAD, PATCH, and OPTIONS requests and verifies the response to these requests.

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
</dependency>

<dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>5.5.5</version>
      <scope>test</scope>
</dependency>

Below are the steps to test a GET Request using Rest Assured:

Step 1 Specify the base URL to the RESTful web service using the RestAssured class.

RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/employees";

Step 2 Every Request in the Rest-Assured library is represented by an interface called RequestSpecification. This interface allows modification of the request, like adding headers or adding authentication details.

requestSpecification = RestAssured.given();

RequestSpecification is imported from the package:

import io.restassured.specification.RequestSpecification;

Step 3 Send the request to the server and receive the response to the request made by REST Assured. This response contains every detail returned by hitting request i.e. response body, response headers, status code, status lines, cookies, etc.

response = requestSpecification.get();

The response is imported from package:

import io.restassured.response.Response;

Step 4 To validate a response like status code or value, we need to acquire a reference. This reference should be of type ValidatableResponse. ValidatableResponse is an interface. A validatable response to a request made by, REST Assured. ValidatableResponse is imported from the package:

import io.restassured.response.ValidatableResponse;

PrettyPrint() It prints the response body if possible and returns it as a string. Pretty printing is possible for content-types JSON, XML, and HTML.

Below is an example of creating a test in Non-BDD format. I have used ValidatableResponse for the assertion of the status. It is also used for the status line of the Response.

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.Test;

public class Get_NonBDDDemo {
    RequestSpecification requestSpecification;
    Response response;
    ValidatableResponse validatableResponse;

    @Test
    public void verifyStatusCode() {

        RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/employees";

        // Create a request specification
        requestSpecification = RestAssured.given();

        // Calling GET method
        response = requestSpecification.get();

        // Let's print response body.
        String resString = response.prettyPrint();
        System.out.println("Response Details : " + resString);

        /*
         * To perform validation on response, we need to get ValidatableResponse type of
         * response
         */
        validatableResponse = response.then();

        // Get status code
        validatableResponse.statusCode(200);

        // Check status line is as expected
        validatableResponse.statusLine("HTTP/1.1 200 OK");

    }
}

If you don’t want to use ValidatableResponse for the assertion, you can use Response from io.restassured .response to get the status code and status line, which are asserted using JUnit.Assert.

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.Assert;
import org.junit.Test;

public class Get_NonBDDResponseDemo {
    RequestSpecification requestSpecification;
    Response response;

    @Test
    public void verifyStatusCode() {

        RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/employees";

        // Create a request specification
        requestSpecification = RestAssured.given();

        // Calling GET method
        response = requestSpecification.get();

        // Let's print response body.
        String resString = response.prettyPrint();
        System.out.println("Response Details : " + resString);

        // Get status line
        String statusLine = response.getStatusLine();
        Assert.assertEquals(statusLine, "HTTP/1.1 200 OK");

        // Get status code
        int statusCode = response.getStatusCode();
        Assert.assertEquals(statusCode, 200);

    }
}

The output of the above program is

Below is the test implemented in BDD Format. In this test, I am asserting the data of Employee of Id 2. I have validated the name of the employee as well as the response message.

1. equalTo is used for assertion, and is imported from a static hamcrest package:

import static org.hamcrest.Matchers.equalTo;

2. given is a static import from package:

import static io.restassured.RestAssured.given;

import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;

public class Get_BDDDemo {

    @Test
    public void verifyUser() {

        // Given
        given()

                // When
                .when()
                .get("http://dummy.restapiexample.com/api/v1/employee/2")

                // Then
                .then()
                .statusCode(200).statusLine("HTTP/1.1 200 OK")

                // To verify booking id at index 3
                .body("data.employee_name", equalTo("Garrett Winters"))
                .body("message", equalTo("Successfully! Record has been fetched."));
    }

}

    given
    
    .when()
    .get("http://dummy.restapiexample.com/api/v1/employee/2")
    
    .then()
    .statusCode(200)
    .statusLine("HTTP/1.1 200 OK")
    
    .body("data.employee_name", equalTo("Garrett Winters"))
    .body("message", equalTo("Successfully! Record has been fetched."));
    

    That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

    Rest Assured Tutorials

    HOME

    RestAssured is a Java-based library that is used to test RESTful Web Services. REST-assured was designed to simplify the testing and validation of REST APIs. It takes influence from testing techniques used in dynamic languages such as Ruby and Groovy.

    Chapter 1 Assertion of JSON in Rest Assured using Hamcrest
    Chapter 2 Extraction from JSON in Rest Assured – JsonPath
    Chapter 3 How to perform multiple assertions in Rest Assured? 
    Chapter 4 How to validate JSON body in Rest Assured?
    Chapter 5 Compare JSON Objects using JSONAssert Library
    Chapter 6 Compare JSON Arrays using JSONAssert Library
    Chapter 7 How to Read JSON with JSON.simple – NEW
    Chapter 8 How to create and write to JSON with JSON.simple – NEW

    JSON Handling and manipulation

    Category 10: XML Manipulations

    XML Handling and manipulation

    Gradle

    Chapter 1 Setup Basic REST Assured Gradle Project In Eclipse IDE

    Frameworks

    Chapter 1 Integration of REST Assured with TestNG
    Chapter 2 Integration of REST Assured with JUnit4
    Chapter 3 Integration of REST Assured with JUnit5
    Chapter 4 Serenity BDD with Cucumber and Rest Assured
    Chapter 5 Serenity BDD with Cucumber and Rest Assured in Gradle
    Chapter 6 How To Create Gradle Project with Cucumber to test Rest API
    Chapter 7 Rest API Test in Cucumber and JUnit4
    Chapter 8 API Automation with REST Assured, Cucumber and TestNG

    Integration of REST Assured with JUnit5

    HOME

    In this tutorial, I’ll create a Test Framework for the testing of REST API using REST Assured and JUnit5 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 JUnit5?

    JUnit 5 is the next generation of JUnit. JUnit 5 is composed of several different modules from three different sub-projects.

    Dependency List:-

    1. REST Assured – 5.3.2
    2. Java 11
    3. JUnit Jupiter API – 5.10.0
    4. JUnit Jupiter Engine – 5.10.0
    5. Maven – 3.8.1
    6. Json – 20230618

    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 learn 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 learn 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 learn How to create a Maven project

    Below is the Maven project structure. Here,

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

    Step 5 – Add REST Assured and JUnit5 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_Junit5_Demo</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>RestAssured_Junit5_Demo</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <rest-assurd.version>5.3.2</rest-assurd.version>
        <json.version>20230618</json.version>
        <hamcrest.version>1.3</hamcrest.version>
        <junit5.version>5.10.0</junit5.version>
        <maven.surefire.report.plugin.version>3.1.2</maven.surefire.report.plugin.version>
        <maven.compiler.plugin.version>3.10.1</maven.compiler.plugin.version>
        <maven.surefire.plugin.version>3.1.2</maven.surefire.plugin.version>
        <maven.compiler.source.version>11</maven.compiler.source.version>
        <maven.compiler.target.version>11</maven.compiler.target.version>
        <maven.site.plugin.version>3.12.0</maven.site.plugin.version>
      </properties>
    
      <dependencies>
    
        <!-- Rest Assured Dependency -->
        <dependency>
          <groupId>io.rest-assured</groupId>
          <artifactId>rest-assured</artifactId>
          <version>${rest-assurd.version}</version>
          <scope>test</scope>
        </dependency>
    
        <!-- JUNIT Jupiter API Dependency-->
        <dependency>
          <groupId>org.junit.jupiter</groupId>
          <artifactId>junit-jupiter-api</artifactId>
          <version>${junit5.version}</version>
          <scope>test</scope>
        </dependency>
    
        <!-- JUNIT Jupiter Engine Dependency-->
        <dependency>
          <groupId>org.junit.jupiter</groupId>
          <artifactId>junit-jupiter-engine</artifactId>
          <version>${junit5.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-compiler-plugin</artifactId>
            <version>${maven.compiler.plugin.version}</version>
            <configuration>
              <source>${maven.compiler.source.version}</source>
              <target>${maven.compiler.target.version}</target>
            </configuration>
          </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-site-plugin</artifactId>
            <version>${maven.site.plugin.version}</version>
          </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>
              <configuration>
                <outputName>JUnit5 Report</outputName>
              </configuration>
            </plugin>
          </plugins>
        </reporting>
    
    </project>
    

    Step 6 – Create the TEST file

    The tests should be written in src/test/java directory. To learn 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.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 createUser() {
    
            JSONObject data = new JSONObject();
    
            data.put("name", "NewUser1");
            data.put("job", "Testing");
    
            // GIVEN
            given()
                    .contentType(ContentType.JSON)
                    .body(data.toString())
    
                    // WHEN
                    .when()
                    .post(BaseURL + "/users")
    
                    // THEN
                    .then()
                    .statusCode(201)
                    .body("name", equalTo("NewUser1"))
                    .body("job", equalTo("Testing"))
                    .log().all();
    
        }
    
        @Test
        public void getUser() {  //Failed Test
    
            // GIVEN
            given()
                    .contentType(ContentType.JSON)
    
                    // WHEN
                    .when()
                    .get(BaseURL + "/users/2")
    
                    // THEN
                    .then()
                    .statusCode(200)
                    .body("data.first_name", equalTo("Janet1"))
                    .log().all();
    
        }
    
    }
    

    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.

    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.

    View the Report

    Right-click on the Junit5 Report.html 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!!

    Logging in Rest Assured

    HOME

    Logging plays an important role in understanding the behaviour of the test. When we are testing an API, it is good to know how the APIs are behaving. We should understand how the request is made and how we received the response from the API. It’s important to check what the headers look like. We also need to see what the body looks like. Additionally, verify what parameters we are providing to the request. All of this helps us debug the test code. It helps us identify the reason for the failure of the test.

    REST Assured, provide support to a different type of logging as shown below:-

    Request Logging

    To log all request specification details including parameters, headers, and body of the request, log().all() needs to be added to post given() section.

    import org.testng.annotations.Test;
    import io.restassured.http.ContentType;
    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.equalTo;
    
    public class RestTests {
    	
    	@Test
        public void requestLoggingDemo() {
     
            String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";
     
            // GIVEN
            given()
                   .log().all()
                   .baseUri("https://dummy.restapiexample.com/api")
                   .contentType(ContentType.JSON)
                   .body(json)
     
            // WHEN
             .when()
                    .post("/v1/create")
     
            // THEN
              .then()
                     .assertThat()
                     .statusCode(200)
                     .body("data.name", equalTo("apitest"))
                     .body("message", equalTo("Successfully! Record has been added."));
     
        }
    
    }
    

    The output of the above program is

    Other different request logging options are:-

    given().log().params(). .. // Log only the parameters of the request
    given().log().body(). .. // Log only the request body
    given().log().headers(). .. // Log only the request headers
    given().log().cookies(). .. // Log only the request cookies
    given().log().method(). .. // Log only the request method
    given().log().path(). .. // Log only the request path
    

    Response Logging

    If you want to print the response body regardless of the status code, you can do

    get("/x").then().log().body()..
    

    This will print the response body regardless of an error occurring.

    import org.testng.annotations.Test;
    import io.restassured.http.ContentType;
    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.equalTo;
    
    public class RestTests {
    
      @Test
    	public void responseLoggingDemo() {
    
    		String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";
    
    		// GIVEN
    		given()
                  .baseUri("https://dummy.restapiexample.com/api")
                  .contentType(ContentType.JSON)
    			  .body(json)
    
    		 // WHEN
    		  .when()
                     .post("/v1/create")
    
    		// THEN
    		  .then()
                     .log().all()
                     .statusCode(200)
                     .body("data.name", equalTo("apitest"))
    				 .body("message", equalTo("Successfully! Record has been added."));
    
    	}
    }
    

    The output of the above program is

    Conditional Logging

    What if you want to perform logging conditionally? For example, log in if validation fails and the status code is equal to 200. Also, log in if the server returns a status code >=400.

    .then().log().ifStatusCodeIsEqualTo(302). .. // Only log if the status code is equal to 302
    .then().log().ifStatusCodeMatches(matcher). .. // Only log if the status code matches the supplied Hamcrest matcher
    
    import org.testng.annotations.Test;
    import io.restassured.http.ContentType;
    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.equalTo;
    
    public class RestTests {
    	
    	@Test
    	public void conditionalResponseLoggingDemo() {
    
    		String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";
    
    		// GIVEN
    		given()
                   .baseUri("https://dummy.restapiexample.com/api")
                   .contentType(ContentType.JSON)
    			   .body(json)
    
    		// WHEN
    		 .when()
                   .post("/v1/create")
    
    		// THEN
    		 .then()
                    .log().ifStatusCodeIsEqualTo(200)
                    .assertThat().statusCode(200)
    				.body("data.name", equalTo("apitest"))
                    .body("message", equalTo("Successfully! Record has been added."));
    
    	}
    
    }
    

    The output of the above program is

    Logging to a text file with Rest Assured

    We will see how we can log all the request and response data to a txt file using Rest Assured.

    1. Create a PrintStream object. You have to provide an object of FileOutputStream() to the PrintStream() constructor. Provide the path to the logging.txt file in FileOutputStream().
    2. REST Assured gives us a filter() method, this filter method accepts RequestLoggingFilter and ResponseLoggingFilter. They have two methods, logRequestTo() and logResponseTo() methods respectively. These methods expect a Stream.
    3. Pass the log stream we created to these methods.
    import org.testng.annotations.Test;
    import io.restassured.filter.log.RequestLoggingFilter;
    import io.restassured.filter.log.ResponseLoggingFilter;
    import io.restassured.http.ContentType;
    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.equalTo;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    
    public class RestTests {
    	
    	@Test
    	public void responsetoFileDemo() throws FileNotFoundException {
    
    		PrintStream log = new PrintStream(new FileOutputStream("logging.txt"));
    
    		String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";
    
    		// GIVEN
    		given()
                   .baseUri("https://dummy.restapiexample.com/api")
                   .contentType(ContentType.JSON)
    				.body(json)
                    .filter(RequestLoggingFilter.logRequestTo(log))
    				.filter(ResponseLoggingFilter.logResponseTo(log))
    
    		// WHEN
    		 .when()
                    .post("/v1/create")
    
    		// THEN
              .then()
                     .log().ifStatusCodeIsEqualTo(200)
                     .assertThat().statusCode(200)
    				 .body("data.name", equalTo("apitest"))
                     .body("message", equalTo("Successfully! Record has been added."));
    
    	}
    }
    

    Mostly we have more than 1 test, and we want to save the log of all the tests in the text file. We can create a @BeforeClass method, and this class contains the code to create the file and append the data to that file.

    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;
    import io.restassured.filter.log.RequestLoggingFilter;
    import io.restassured.filter.log.ResponseLoggingFilter;
    import io.restassured.http.ContentType;
    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.equalTo;
    
    public class LogTest {
    	
    	 public PrintStream log ;
    	 RequestLoggingFilter requestLoggingFilter;
    	 ResponseLoggingFilter responseLoggingFilter;
    	
    	@BeforeClass
    	public void init() throws FileNotFoundException {
    		
    		 log = new PrintStream(new FileOutputStream("test_logging.txt"),true);	
    		 requestLoggingFilter = new RequestLoggingFilter(log);
    		 responseLoggingFilter = new ResponseLoggingFilter(log);
    		 
    	}
    	
    	@Test
    	public void test1() {
    
    		// Given
    		given()
    
             .contentType(ContentType.JSON)
             . filters(requestLoggingFilter,responseLoggingFilter)
           
              .when()
                 .get("https://dummy.restapiexample.com/api/v1/employee/2")
    				
               .then()
               		.log().ifStatusCodeIsEqualTo(200)
               		.assertThat().statusCode(200).statusLine("HTTP/1.1 200 OK")
    				
               		// To verify booking id at index 2
    				.body("data.employee_name", equalTo("Garrett Winters"))
    				.body("message", equalTo("Successfully! Record has been fetched."));
    	}
    	
    	@Test
    	public void test2() {
    
    		// Given
    		given()
    
             .contentType(ContentType.JSON)
             . filters(requestLoggingFilter,responseLoggingFilter)
           
              .when()
                 .get("https://dummy.restapiexample.com/api/v1/employee/1")
    				
               .then()
               .log().ifStatusCodeIsEqualTo(200)
               .assertThat().statusCode(200).statusLine("HTTP/1.1 200 OK")
    				// To verify booking id at index 1
    				.body("data.employee_name", equalTo("Tiger Nixon"))
    				.body("message", equalTo("Successfully! Record has been fetched."));
    	}
    
    	
    	
    	@Test
        public void test3() throws FileNotFoundException {
     
            
            String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";
     
            // GIVEN
            given()
                   .baseUri("https://dummy.restapiexample.com/api")
                   .contentType(ContentType.JSON)
                    .body(json)
                   .filters(requestLoggingFilter,responseLoggingFilter)
     
            // WHEN
             .when()
                    .post("/v1/create")
     
            // THEN
              .then()
                     .log().ifStatusCodeIsEqualTo(200)
                     .assertThat().statusCode(200)
                     .body("data.name", equalTo("apitest"))
                     .body("message", equalTo("Successfully! Record has been added."));
     
        }
    	
    }
    
    

    The below file shows that the log for multiple requests is saved here.

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

    How to test PATCH Request using Rest Assured
    How to test POST request from JSON Object in Rest Assured
    How to test POST JSON Object request using Java Map in Rest Assured
    How to create JSON Array Request Body – org.json
    Assertion of JSON in Rest Assured using Hamcrest
    Extraction from JSON in Rest Assured

    How to install Plugins from Jenkins CLI?

    HOME

    In the previous tutorial, I have explain the steps to install plugins in Jenkins from Jenkins UI. In this tutorial, we will install the plugins from Jenkins CLI.

    Step 1 – Verify that the plugin is present in Available option in Plugin Manager

    Login to Jenkins UI.

    Provide a username and password and click on the Sign-in Button.

    Click on the Manage Jenkins. Choose Manage Plugins.

    On the Plugin Manager Page, go to the Available option and type Serenity or any plugin of your choice. Here we can see that Serenity is present in the Available option.

    Step 2 – Go to Jenkins CLI

    Click on the Manage Jenkins. Choose Jenkins CLI.

    Step 3 – Download Jenkins CLI

    Download jenkins-cli.jar from the Jenkins CLI page as shown in the image.

    Step 4 – Run the Jenkins CLI command

    Open Windows or PowerShell command line and go to the location where the jenkins-cli.jar file is placed on your machine.

    Type the below command.

    java -jar jenkins-cli.jar -s http://localhost:8080/ who-am-i
    

    Here, we have not provided the login credentials to login to Jenkins, so the system shows Authenticated as anonymous.

    As can be seen in the below image, we need to use -auth to login to Jenkins.

    In this case, I have used the below command to login to the Jenkins

    java -jar jenkins-cli.jar -s http://localhost:8080/ -auth Username:password who-am-i
    

    To install the plugin, use the below command:

    java -jar jenkins-cli.jar -s http://localhost:8080/ -auth username:password install-plugin serenity:1.4
    

    serenity is the name of the plugin and 1.4 is the version of the plugin.

    You can see that the Serenity plugin is getting installed.

    Now, we need to restart the Jenkins. Use the below command to restart the Jenkins

    java -jar jenkins-cli.jar -s http://localhost:8080/ -auth username:password safe-restart
    

    safe-restart plugin allows you to restart Jenkins safely. Jenkins restarts once all running jobs are finished.

    To verify that the Serenity plugin is installed or not in Jenkins, please go to Manage Jenkins -> Plugin Manager ->Installed -> Serenity Plugin.

    Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

    Integrate Gradle project with Jenkins
    How to generate HTML Reports in Jenkins
    How to Schedule a Jenkins Job
    Build History Metrics in Jenkins
    How to create Jenkins pipeline for Extent Report
    How to run parameterized Selenium tests in Jenkins