XmlPath in Rest Assured

HOME

 <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>xml-path</artifactId>
            <version>5.5.0</version>
 </dependency>

<shopping>
 <category type="groceries">
 <item>
 <name>Chocolate</name>
 <price>10</price>
 </item>
 <item>
 <name>Coffee</name>
 <price>20</price>
 </item>
 </category>
 <category type="supplies">
 <item>
 <name>Paper</name>
 <price>5</price>
 </item>
 <item quantity="4">
 <name>Pens</name>
 <price>15</price>
 </item>
 </category>
 <category type="present">
 <item when="Aug 10">
 <name>Kathryn's Birthday</name>
 <price>200</price>
 </item>
 </category>
 </shopping>

import io.restassured.path.xml.XmlPath;
import io.restassured.path.xml.element.Node;
import org.junit.Test;

import java.util.List;


public class XMLPath_Demo {

    String body = "<shopping>\n" +
            " <category type=\"groceries\">\n" +
            " <item>\n" +
            " <name>Chocolate</name>\n" +
            " <price>10</price>\n" +
            " </item>\n" +
            " <item>\n" +
            " <name>Coffee</name>\n" +
            " <price>20</price>\n" +
            " </item>\n" +
            " </category>\n" +
            " <category type=\"supplies\">\n" +
            " <item>\n" +
            " <name>Paper</name>\n" +
            " <price>5</price>\n" +
            " </item>\n" +
            " <item quantity=\"4\">\n" +
            " <name>Pens</name>\n" +
            " <price>15</price>\n" +
            " </item>\n" +
            " </category>\n" +
            " <category type=\"present\">\n" +
            " <item when=\"Aug 10\">\n" +
            " <name>Kathryn's Birthday</name>\n" +
            " <price>200</price>\n" +
            " </item>\n" +
            " </category>\n" +
            " </shopping>";

    @Test
    public void test() {
        XmlPath xmlPath = new XmlPath(body);

        //Get the name of the first category item:
        String name = xmlPath.get("shopping.category.item[0].name");
        System.out.println("Item Name: " + name);

        // Get the price of the first category price:
        String chocolatePrice = xmlPath.get("shopping.category.item[0].price");
        System.out.println("chocolatePrice :" + chocolatePrice);

        // Get the price of the second category price:
        String coffeePrice = xmlPath.get("shopping.category.item[1].price");
        System.out.println("coffeePrice :" + coffeePrice);

        //To get the number of category items:
        int itemSize = xmlPath.get("shopping.category.item.size()");
        System.out.println("Item Size: " + itemSize);

       // Get a specific category:
        Node category = xmlPath.get("shopping.category[0]");
        System.out.println("category :" + category);
        
        //To get the number of categories with type attribute equal to 'groceries':
        int groceryCount = xmlPath.get("shopping.category.findAll { it.@type == 'groceries' }.size()");
        System.out.println("groceryCount :" + groceryCount);

        //Get all items with price greater than or equal to 10 and less than or equal to 20:
        List<Node> itemsBetweenTenAndTwenty = xmlPath.get("shopping.category.item.findAll { item -> def price = item.price.toFloat(); price >= 10 && price <= 20 }");
        System.out.println("itemsBetweenTenAndTwenty :" + itemsBetweenTenAndTwenty);

       // Get the chocolate price:
        int priceOfChocolate = xmlPath.getInt("**.find { it.name == 'Chocolate' }.price");
        System.out.println("priceOfChocolate :" + priceOfChocolate);
    }
}

Parameterizing REST Assured Tests with junit4-dataprovider Dependency

HOME

<!-- Data Provider -->
 <dependency>
      <groupId>com.tngtech.junit.dataprovider</groupId>
      <artifactId>junit4-dataprovider</artifactId>
      <version>${junit.dataprovider.version}</version>
      <scope>test</scope>
</dependency>

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

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

  <properties>
    <rest-assured.version>5.4.0</rest-assured.version>
    <junit.version>4.13.2</junit.version>
    <junit.dataprovider.version>2.10</junit.dataprovider.version>
    <maven.compiler.plugin.version>3.12.1</maven.compiler.plugin.version>
    <maven.surefire.plugin.version>3.2.3</maven.surefire.plugin.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

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

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

    <!-- Data Provider -->
    <dependency>
      <groupId>com.tngtech.junit.dataprovider</groupId>
      <artifactId>junit4-dataprovider</artifactId>
      <version>${junit.dataprovider.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>
          <testFailureIgnore>true</testFailureIgnore>
        </configuration>
      </plugin>

    </plugins>
  </build>
</project>

@RunWith(DataProviderRunner.class)

 @DataProvider
    public static Object[][] responseData() {
        return new Object[][] {
                { "1", "George", "Bluth" },
                { "2", "Janet", "Weaver" },
                { "3", "Emma", "Wong" },
                { "4", "Eve", "Holt" }
        };
    }

import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;

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

@RunWith(DataProviderRunner.class)
public class ParameterizedTets {

    @DataProvider
    public static Object[][] responseData() {
        return new Object[][] {
                { "1", "George", "Bluth" },
                { "2", "Janet", "Weaver" },
                { "3", "Emma", "Wong" },
                { "4", "Eve", "Holt" }
        };
    }

    @Test
    @UseDataProvider("responseData")
    public void verifyResponse(String id, String expectedFirstName, String expectedLastName)
    {
        given().
                when().
                pathParam("id", id).
                get("https://reqres.in/api/users/{id}").
                then().
                assertThat().
                statusCode(200).
                body("data.first_name", equalTo(expectedFirstName)).
                body("data.last_name", equalTo(expectedLastName));
    }
}

How to handle async requests in API Testing

HOME

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

package org.example;

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

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

import static org.hamcrest.MatcherAssert.assertThat;


public class AsyncRequest_Demo {

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

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

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

    }
}

How to insert data in SQL Server using Java

HOME

jdbc:<driver protocol>:<driver connection details>
MS MySql Server - jdbc:odbc:DemoDSN
MySQL - jdbc:mysql://localhost:3306/demodb
Oracle - jdbc:orac;e:thin@myserver:1521:demodb
String dbUrl = "jdbc:mysql://localhost:3306/demo";
String username = "student";
String password = "student1$";

Connection conn = DriverManager.getConnection(dbUrl,username,password)
Statement stmt = conn.createStatement();

 int rowAffected = stmt.executeUpdate(
                    "insert into employees (last_name, first_name, email, department,salary) values ('Singh', 'Vibha','vibha.test@gmail.com', 'QA', 85000)");

<dependencies>
    <dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <version>8.2.0</version>
</dependency>

package org.example;

import java.sql.*;

public class InsertRow_Demo {
    public static void main(String[] args) throws SQLException {

        Connection conn;
        Statement stmt = null;
        ResultSet result = null;
        ResultSet result1 = null;
        ResultSet result2 = null;

        String dbUrl = "jdbc:mysql://localhost:3306/demo";
        String username = "student";
        String password = "student1$";

        try {
            //Get a connection to database
            conn = DriverManager.getConnection(dbUrl, username, password);

            System.out.println("Database connection is successful\n");

            //Create a statement
            stmt = conn.createStatement();

            System.out.println("Inserting a new employee\n");

            int rowAffected = stmt.executeUpdate(
                    "insert into employees (last_name, first_name, email, department,salary) values ('Singh', 'Vibha','vibha.test@gmail.com', 'QA', 85000)");

            System.out.println("No of rows inserted :" + rowAffected);

            //Execute the SQL Query
            result = stmt.executeQuery("Select * from employees");

            //Process the result set
            while (result.next()) {
                System.out.println("First_Name :" + result.getString("first_name") + " , " + ("Last_Name :" + result.getString("last_name")));

            }


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

Java Access Modifiers: Explained with Examples

HOME

There are two types of access modifiers in Java – access modifiers and non-access modifiers.

The access modifier of Java specifies the scope of the variable, method, constructor, or class. We can change the access level of variables, methods, constructors, and classes by applying access modifiers to them.

There are 4 types of access modifiers.

  1. Private: The code is only accessible within the declared class. It cannot be accessed from outside the class.
  2. Default: The code is only accessible in the same package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  3. Protected: The code is accessible in the same package and subclasses. If you do not make the child class, it cannot be accessed from outside the package.
  4. Public: The class is accessible by any other class. It can be accessed from within the class, outside the class, within the package, and outside the package.

Java Access Modifiers

Private

The private access modifier is accessible only within the class.

In this example, I have created one class – Demo_1 in package Parent_A. It contains a private variable and a private method. We can access private variables and methods within the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private void display() { // private method
		System.out.println("Display private method");
	}

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();

		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

In the below example, we have 2 classes – Demo_1 and Demo_2. Class Demo_1 contains private data members and private methods. We are accessing these private members from outside the class, another class Demo_2 so there is a compile-time error.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private void display() { // private method
		System.out.println("Display private method");
	}

}
package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

Private Constructor

In the below example, the private constructor is accessible within the class.

package Parent_A;

public class Demo_1 {
    private int x = 10; // private variable

    private Demo_1() {

        System.out.println("Private Constructor: Value of x : " + x);
    }

    private void display() { // private method
        System.out.println("Display private method");
    }

    public static void main(String[] args) {

        Demo_1 obj1 = new Demo_1();

    }
}

If you make any class constructor private, you cannot create the instance of that class from outside the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private Demo_1() {

		System.out.println("Private Constructor");
	}

	private void display() { // private method
		System.out.println("Display private method");
	}

}

package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
	}

}

Default

If we don’t use any modifier, it is treated as a default access modifier. The default modifier is accessible only within the package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected and public.

In this example, we have created two classes – Demo_1 and Demo_2 in package – Parent_A. We are accessing the class Demo_2 from within its package, since it is default, so it can be accessed from within the package.

package Parent_A;

public class Demo_1 {

    int x = 10; // default variable

    Demo_1() {

        System.out.println("Default Constructor: Value of x : " + x);
    }

    void display() { // default method
        System.out.println("Display default method");
    }

}

package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

Protected

The protected access modifier is accessible within the package and outside the package but through inheritance only.

The protected access modifier can be applied to the data member, method, and constructor. It can’t be applied to the class.

In the below example, I have created two packages Parent_A and Parent_B. The class Demo_1 of Parent_A package is public, so can be accessed from outside the package. However the variable, constructor, and method of this package are declared as protected, so it can be accessed from outside the class only through inheritance.

package Parent_A;

public class Demo_1 {
    
    protected  int x = 10; // protected variable

    protected Demo_1() {

        System.out.println("Protected Constructor: Value of x : " + x);
    }

    protected void display() { // protected method
        System.out.println("Display Protected method");
    }

}

package Parent_B;

import Parent_A.Demo_1;

public class Demo_3 extends Demo_1{

    public static void main(String[] args) {

        Demo_3 obj1 = new Demo_3();
        System.out.println("Value of X :" + obj1.x);
        obj1.display();
    }

}

Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

In the below example, I have created two packages Parent_A and Parent_B. The variable, constructor, and method of this package are declared as public, so it can be accessed from outside the class or outside the package.

package Parent_A;

public class Demo_1 {
    public   int x = 10; // public variable

    public  Demo_1() {

        System.out.println("Public Constructor: Value of x : " + x);
    }

    public  void display() { // public method
        System.out.println("Display Public method");
    }

}

package Parent_B;

import Parent_A.Demo_1;

public class Demo_4 {

    public static void main(String[] args) {

        Demo_1 obj1 = new Demo_1();

        System.out.println("Value of X :" + obj1.x);
        obj1.display();

    }

}

Keyword Driven Framework Tutorial – Selenium

HOME

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

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

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <selenium.version>4.21.0</selenium.version>
    <testng.version>7.10.2</testng.version>
    <poi.version>5.2.5</poi.version>
    <poi.ooxml.version>5.2.5</poi.ooxml.version>
    <commons.version>2.16.1</commons.version>
    <maven.surefire.plugin.version>3.2.5</maven.surefire.plugin.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>
  </properties>

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

    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>${testng.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>${poi.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>${poi.ooxml.version}</version>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>${commons.version}</version>
    </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>

package com.example.pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

public class BasePage {
    public WebDriver driver;

    public BasePage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver,this);
    }

}

package com.example.keywords;

import com.example.utils.ExcelUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class LoginPageKeywords extends BasePage{

    public LoginPageKeywords(WebDriver driver) {
        super(driver);

    }

    @FindBy(name = "username")
    public WebElement userName;

    @FindBy(name = "password")
    public WebElement password;

    @FindBy(xpath = "//*[@class='oxd-form']/div[1]/div/span")
    public WebElement missingUsernameErrorMessage;

    @FindBy(xpath = "//*[@class='oxd-form']/div[2]/div/span")
    public WebElement missingPasswordErrorMessage;

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

    @FindBy(xpath = "//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/div/div[1]/div[1]/p")
    public  WebElement errorMessage;


    public void enterUsername(String strUserName) {
        userName.sendKeys(strUserName);
    }

    public void enterPassword(String strPassword) {
        password.sendKeys(strPassword);
    }

    public void login() {
        loginBtn.click();
    }

    public void login(String strUserName, String strPassword) {

        userName.sendKeys(strUserName);
        password.sendKeys(strPassword);
    }

    public String getMissingUsernameText() {
        return missingUsernameErrorMessage.getText();
    }

    public String getMissingPasswordText() {
        return missingPasswordErrorMessage.getText();
    }

    public String getErrorMessage() {
        return errorMessage.getText();
    }

    public LoginPageKeywords saveTestResults(int row, int column) {
        ExcelUtils.rowNumber = row ;
        ExcelUtils.columnNumber = column;
        return this;
    }

}

package com.example.keywords;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class HomePageKeywords extends BasePage {

    public HomePageKeywords(WebDriver driver) {
        super(driver);

    }

    @FindBy(xpath = "//*[@id='app']/div[1]/div[1]/header/div[1]/div[1]/span/h6")
    public  WebElement homePageUserName;

    public String verifyHomePage() {
        return homePageUserName.getText();
    }
}

package com.example.utils;

import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelUtils {


    public static String testDataExcelPath = null; //Location of Test data excel file
    private static XSSFWorkbook excelWorkBook; //Excel WorkBook
    private static XSSFSheet excelWorkSheet; //Excel Sheet
    private static XSSFCell cell; //Excel cell
    private static XSSFRow row; //Excel row
    public static int rowNumber; //Row Number
    public static int columnNumber; //Column Number
    public static FileInputStream ExcelFile;

    public static DataFormatter formatter;
    public static FileOutputStream fileOut;


    // This method has two parameters: "Test data excel file name" and "Excel sheet name"
    // It creates FileInputStream and set excel file and excel sheet to excelWBook and excelWSheet variables.
    public static void setExcelFileSheet(String sheetName) throws IOException {

        testDataExcelPath = Constants.currentDir + Constants.resourcePath;

        // Open the Excel file
        ExcelFile = new FileInputStream(testDataExcelPath + Constants.testDataExcelFileName);
        excelWorkBook = new XSSFWorkbook(ExcelFile);
        excelWorkSheet = excelWorkBook.getSheet(sheetName);

    }

    //This method reads the test data from the Excel cell.
    public static String getCellData(int rowNum, int colNum) {
        cell = excelWorkSheet.getRow(rowNum).getCell(colNum);
        formatter = new DataFormatter();
        return formatter.formatCellValue(cell);
    }

    //This method takes row number as a parameter and returns the data of given row number.
    public static XSSFRow getRowData(int rowNum) {
        row = excelWorkSheet.getRow(rowNum);
        return row;
    }

    //This method gets excel file, row and column number and set a value to the that cell.
    public static void setCellData(String value, int rowNum, int colNum) throws IOException {
        row = excelWorkSheet.getRow(rowNum);
        cell = row.getCell(colNum);
        if (cell == null) {
            cell = row.createCell(colNum);
            cell.setCellValue(value);
        } else {
            cell.setCellValue(value);
        }

        // Write to the workbook
        fileOut = new FileOutputStream(testDataExcelPath + Constants.testDataExcelFileName);
        excelWorkBook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    }
}

import com.example.tests.BaseTests;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import java.io.IOException;

public class TestListener implements ITestListener {

    private static String getTestMethodName(ITestResult iTestResult) {
        return iTestResult.getMethod().getConstructorOrMethod().getName();
    }

    @Override
    public void onStart(ITestContext iTestContext) {
        System.out.println("I am in onStart method :" + iTestContext.getName());
    }

    @Override
    public void onFinish(ITestContext iTestContext) {
        System.out.println("I am in onFinish method :" + iTestContext.getName());
    }

    @Override
    public void onTestStart(ITestResult iTestResult) {
        System.out.println("I am in onTestStart method :" + getTestMethodName(iTestResult) + ": start");
    }

    @Override
    public void onTestSuccess(ITestResult iTestResult)  {
        System.out.println("I am in onTestSuccess method :" + getTestMethodName(iTestResult) + ": succeed");
        try {
            ExcelUtils.setCellData("PASSED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onTestFailure(ITestResult iTestResult)  {
        System.out.println("I am in onTestFailure method :" + getTestMethodName(iTestResult) + " failed");
        try {
            ExcelUtils.setCellData("FAILED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onTestSkipped(ITestResult iTestResult) {
        System.out.println("I am in onTestSkipped method :" + getTestMethodName(iTestResult) + ": skipped");
        try {
            ExcelUtils.setCellData("SKIPPED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
        System.out.println("Test failed but it is in defined success ratio " + getTestMethodName(iTestResult));
    }
}

package com.example.utils;

public class Constants {

    public static final String testDataExcelFileName = "Test_Cases.xlsx"; //Global test data excel file
    public static final String currentDir = System.getProperty("user.dir");  //Main Directory of the project
    public static final String resourcePath = "\\src\\test\\resources\\";  //Main Directory of the project
    public static final String excelTestDataName = "LoginData";
}

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

import java.time.Duration;

public class BaseTests {

    public static WebDriver driver;
    public final static int TIMEOUT = 10;

    @BeforeMethod
    public void setup() {

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");
        options.addArguments("--headless");
        driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("https://opensource-demo.orangehrmlive.com/");
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));

    }

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

}

package com.example.tests;

import com.example.keywords.HomePageKeywords;
import com.example.keywords.LoginPageKeywords;
import com.example.utils.Constants;
import com.example.utils.ExcelUtils;
import com.example.utils.TestListener;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import java.io.IOException;

@Listeners({TestListener.class })
public class LoginPageTests extends BaseTests {

    String username;
    String password;
    String actualResponse;
    String expectedResponse;


    @BeforeTest
    public void setupTestData() throws IOException {

        System.out.println("Setup Test Data");
        ExcelUtils.setExcelFileSheet(Constants.excelTestDataName);
    }

    @Test
    public void validCredentials() throws IOException {

        username = ExcelUtils.getCellData(2,5);
        password = ExcelUtils.getCellData(3,5);
        expectedResponse = ExcelUtils.getCellData(5,6);

        LoginPageKeywords loginPage = new LoginPageKeywords(driver);

        loginPage.enterUsername(username);
        loginPage.enterPassword(password);
        loginPage.login();

        HomePageKeywords homePage = new HomePageKeywords(driver);
        actualResponse = homePage.verifyHomePage();

        ExcelUtils.setCellData(actualResponse,5,7);
        saveTestResults(5,8);
        Assert.assertEquals(actualResponse,expectedResponse);

    }

    @Test
    public void invalidCredentials() throws IOException {

        username = ExcelUtils.getCellData(9,5);
        password = ExcelUtils.getCellData(10,5);
        expectedResponse = ExcelUtils.getCellData(12,6);

        LoginPageKeywords loginPage = new LoginPageKeywords(driver);

        loginPage.enterUsername(username);
        loginPage.enterPassword(password);
        loginPage.login();

        actualResponse = loginPage.getErrorMessage();

        ExcelUtils.setCellData(actualResponse,12,7);
        saveTestResults(12,8);
        Assert.assertEquals(actualResponse,expectedResponse);

    }

}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Keyword Driven Framework">
    <test name="Login Test">
        <classes>
            <class name="com.example.tests.LoginPageTests"/>
        </classes>
    </test> <!-- Test -->
</suite> <!-- Suite -->

mvn clean test

Update Specific Values in Java Properties File: Step-by-Step Guide

HOME

We want to replace the password from Admin to Admin123.

 Properties properties = new Properties();

 FileInputStream fileInputStream = new FileInputStream("src/test/resources/userCreated.properties");
 properties.load(fileInputStream);

properties.setProperty("password", "Admin123");

FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/userCreated.properties");

// store() method is used to write the properties into properties file
properties.store(fileOutputStream, "File is modified");
package org.example;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class ModifyPropertiesExample {

    public static void main(String args[]) {

        // Creating properties files from Java program
        Properties properties = new Properties();

        try {
            FileInputStream fileInputStream = new FileInputStream("src/test/resources/userCreated.properties");
            properties.load(fileInputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        properties.setProperty("password", "Admin123");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/userCreated.properties");

            // store() method is used to write the properties into properties file
            properties.store(fileOutputStream, "File is modified");

            fileOutputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Rest API Multiple Choice Answers – MCQ2

HOME
















Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=



https://api.example.com/users?id=123&name=Vibha






Rest API Multiple Choice Questions – MCQ2

HOME


Answer


Answer


Answer


Answer


Answer


@Test
public void test() {
 
    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."));
 }

Answer


  @Test
    public void test() {
 
        JSONObject data = new JSONObject();
 
        data.put("employee_name", "MapTest");
        data.put("profile_image", "test.png");
 
        RestAssured
                .given().contentType(ContentType.JSON).body(data.toString())
 
                .when().post("https://dummy.restapiexample.com/api/v1/create")
 
                .then().assertThat().statusCode(201)
                .body("data.employee_name", equalTo("MapTest"))
                .body("message", equalTo("Successfully! Record has been added."));
 
    }
}
@Test
public void test() {
 
   RestAssured
      .given().contentType(ContentType.JSON).body()
 
       .when().post("https://dummy.restapiexample.com/api/v1/create")
 
       .then().assertThat().statusCode(200)
       .body("data.employee_name", equalTo("MapTest"));
 
    }
}
@Test
public void test() {
 
    RestAssured
        .given().contentType(ContentType.JSON).body(data.toString())
 
        .when().post("https://dummy.restapiexample.com/api/v1/create")
 
         .then().assertThat().statusCode(200)
         .body("data.employee_name", equalTo("MapTest"));
 
    }
}

Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer


Answer

====================================================================

Java Properties: Storing and Writing Data in XML Format

HOME

Properties properties = new Properties();
properties.setProperty("username", "Vibha");
properties.setProperty("password", "XML");
 FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/userCreatedXML.xml");

properties.storeToXML(fileOutputStream, "Sample XML Properties file created");
package org.example;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class WritePropertiesXMLExample {

    public static void main(String args[]) {

        Properties properties = new Properties();
        properties.setProperty("username", "Vibha");
        properties.setProperty("password", "XML");

        try {
            // userCreated.properties is created at the mentioned path
            FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/userCreatedXML.xml");

            // storeToXML() method is used to write the properties into properties xml file
            properties.storeToXML(fileOutputStream, "Sample XML Properties file created");
            fileOutputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}