How to handle Web tables using Java and Selenium Webdriver

How to handle Web tables using Java and Selenium Webdriver

What are Web Tables?

Web tables, also known as HTML tables, are a widely used format for displaying data on web pages. They allow for a structured representation of information in rows and columns, making it easy to read and manipulate data. Selenium WebDriver, a powerful tool for web browser automation, provides the functionality to interact with these tables programmatically. This capability is beneficial for tasks like web scraping, automated testing, and data validation. In this blog, we will see how to extract data from Web tables in Java-Selenium.

Identify web table from your webpage:

To effectively identify and interact with web tables using Selenium, it’s crucial to understand the HTML structure of tables and the specific tags used. Here’s an overview of the key table-related HTML tags

A typical HTML table consists of several tags that define its structure:

  • <table>: The main container for the table.
  • <thead>: Defines the table header, which contains header rows (<tr>).
  • <tbody>: Contains the table body, which includes the data rows.
  • <tr>: Defines a table row.
  • <th>: Defines a header cell in a table row.
  • <td>: Defines a standard data cell in a table row.

How to Identify Web Tables?

As we have got  an idea of what is Web Table and how to identify WebTables on the webpage, now we will see how to extract the table data.
We will be using “https://www.globalsqa.com/angularJs-protractor/WebTable/

As a demo website, here you will get a sample WebTable with fields like first name, last name, email, etc. Here we have applied a filter for email to minimize the size of the table.

We will be starting by launching the browser and navigating to the webpage. We have applied a filter for the email “PolGermain@whatever.com”, you can change it as per your requirement.

Once we get the filtered data from the table, now we need to locate the table and get the number of rows. The table will have multiple rows so, we need to use a list to store all the rows.

As we have stored all the rows in the list, now we need to iterate through each rows to fetch the columns and store the column data in another list.

Example :

Abc1
Xyz2
table has 2 rows and 2 columns

When we are iterating through the 1st row we will get data as Abc and 1 and store it in the list ’as rowdata[Abc, 1] similarly data from the 2nd row will be stored as rowdata[Xyz, 2].When we are iterating through the 2nd row the data from the 1st row will be overwritten.
That’s why we will need one more list ‘webRows ’ to store all the rows.
In the below code snippet, here we are iterating through all the columns from each row one by one and finally storing all the rows in the list WebRows.

How to access table data with the column index?

We have successfully extracted the table data now you can use this data as per your requirement

To do this we need to iterate through the list ‘webRows’ where we have our table data stored. We will be accessing all the columns by their index. In this case, you should know the column index you want to access.  The column index always starts from 0.

Below is the complete code snippet for the above-mentioned steps. You need to update related Xpaths in case you are not able to access the rows and columns with the given Xpaths.

web tables in selenium

When you execute the above code, you will get output in the below format

[Pol, Germain, 49, PolGermain@whatever.com, 1020.1597184937436]
Germain
[Pol, Germain, 62, PolGermain@whatever.com, 911.4520444579008]
Germain
[Pol, Germain, 10, PolGermain@whatever.com, 2809.911328973954]
Germain

Instead of accessing data by the index, you can access it using the column index also, and to do that you need to use the HashMaps instead of lists. HashMap will help to store column headers as keys and column data as values

Example:

NameId
Abc1
Xyz2
Table has 3 rows and 2 columns

Here Name and ID will be your keys and Abc, 1 and Xyz, 2 will be the values.

How to store and access table data using HashMap?

The code snippet below shows how to use HashMap to store data in key-value format.

web tables in selenium

Output-

size-4
Germain
{firstName=Pol, lastName=Germain, balance=1527.3558523201625, age=28, email=PolGermain@whatever.com}
Germain
{firstName=Pol, lastName=Germain, balance=250.18122282042322, age=20, email=PolGermain@whatever.com}
Germain
{firstName=Pol, lastName=Germain, balance=274.9486946306141, age=3, email=PolGermain@whatever.com}
Germain
{firstName=Pol, lastName=Germain, balance=1176.6629976866143, age=10, email=PolGermain@whatever.com}

Refer to the following GitHub repository for How to automate web tables in Java-Selenium.
https://github.com/priyanka1970/WebTables_with_Java_Selenium

Conclusion-

In this blog, we’ve delved into the powerful capabilities of Selenium WebDriver for handling web tables in Java. WebTables are a crucial part of web applications, often used to display large amounts of data in an organized manner. In Java Selenium, handling these WebTables efficiently is a key skill for any test automation engineer. Throughout this blog, we’ve explored various techniques to interact with WebTables, including locating tables, accessing rows and cells, iterating through table data, and performing actions like sorting and filtering.

Click here for more blogs on software testing and test automation.

How to execute Playwright-Js tests on BrowserStack

How to execute Playwright-Js tests on BrowserStack

        

Introduction:

At times, certain project specifications demand comprehensive testing of a web application across a diverse range of web browsers and their varying versions. Maintaining consistent functionality, visual appearance, and user engagement is essential.

To execute this type of cross-browser testing efficiently, there are two primary approaches:

  • One involves manual testing, where the website is examined across multiple browsers and devices. 
  • The other approach entails leveraging specialized tools and services that replicate distinct browser environments. 

Particularly, BrowserStack stands out as a tool that has garnered considerable attention in this field, thanks to its intuitive user interface.

Executing test cases on BrowserStack is crucial for QA teams to ensure the compatibility, functionality, and performance of websites and applications across a wide range of real browsers and devices. 

It helps identify bugs, responsive design issues, and user experience problems, while also supporting automated testing and real environment testing. 

BrowserStack eliminates the need for local testing infrastructure, reducing costs and enhancing overall testing efficiency.                                                   

So first let’s talk about the Basic Framework where we can automate test cases using the BDD approach to execute tests on a browser on the local machine. 

So for this instead of explaining it from scratch here again, You can explore my blog where I have explained How to create a BDD automation framework using Cucumber in JavaScript and Playwright.

This blog gives you step-by-step guidance on how to Create Feature files, Steps files, Page Files, and various other utilities to make the framework more reusable and robust. So here is the link to this blog: https://shorturl.at/bjuvU

You can also use the below link to access the BDD automation framework using Cucumber in JavaScript: https://github.com/spurqlabs/Playwright_JS_BDD_Framework

Pre-requisite:

To get started with BrowserStack implementation first store your BrowserStack username and access key in the .env file.
To get the username and access key to navigate to your BrowserStack account. Click on Access key dropdown from dashboard and you will be able to see your username and access key.

Here you will be able to see your account details. Copy your Username and Access Key and store it in a .env file as shown below. To execute tests on BrowserStack set the Browserstack variable to ‘true’.

Browserstack = true
BROWSERSTACK_USERNAME='browserstack_usename'
BROWSERSTACK_ACCESS_KEY='browserstack_accessKey'

Now to set BrowserStack configurations Create a file as “Browserstack.js”, as you can see I have created a “Browserstack.js file” in the Utility folder.

Playwright Framework


Here are the essential BrowserStack configurations to integrate into this file.

const cp = require('child_process')
const playwrightClientVersion = cp
    .execSync('npx playwright --version')
    .toString()
    .trim()
    .split(' ')[1]
function caps() {
    return {
        'browser': 'playwright-chromium',
        'os': 'Windows',
        'os_version': '10',
        'browserstack.username': process.env.BROWSERSTACK_USERNAME,
        'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY,
        'client.playwrightVersion': playwrightClientVersion
    }
}
module.exports = { caps }
.execSync('npx playwright --version')
    .toString()
    .trim()
    .split(' ')[1]

.execSync:

The playwrightClientVersion variable is declared and assigned the output of the shell command executed using execSync from the child_process module.

.execSync('npx playwright --version’):

The command executed is npx playwright –version, which retrieves the version of the Playwright framework installed on the system. The output is converted to a string, trimmed to remove leading or trailing whitespace, and then split into an array based on spaces. The second element of the array (split(‘ ‘)[1]) represents the Playwright’s version.

caps():

This function is responsible for generating a configuration object used for browser testing with the BrowserStack platform and Playwright framework. It returns an object that contains configuration options for browser testing like browser, os, os_version, etc.

process.env.BROWSERSTACK_USERNAME, process.env.BROWSERSTACK_ACCESS_KEY:

These are the variables from the .env file. If you are not using a .env file you can directly pass the BrowserStack username and access key.

As we have all the configurations ready, we will set up a test environment to execute tests on BrowserStack. Use the file where you have your Before and After methods. In the playwright-Js Framework we have these methods stored in the ‘TestHooks.js file’ so will update that file as below.

const { Before, AfterAll } = require('@cucumber/cucumber')
const page = require('@playwright/test')
const path = require('path');
const { chromium } = require('playwright')
require('dotenv').config({
  path: path.join(__dirname, '../.env'),
});
Before(async (scenario) => {
  if (process.env.BrowserStack === 'true') {
    try {
      const capabilitiesBr = require('./BrowserStack').caps(scenario)
      global.browser = await chromium.connect({
        wsEndpoint: `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(capabilitiesBr))}`,
      })
      viewport = {
        width: 1920,
        height: 900,
      }
    } catch (e) 
      console.error('Error connecting to BrowserStack', e)
    }
  } else {
    global.browser = await page.chromium.launch({ headless: false })
  }
  const context = await browser.newContext()
  global.page = await context.newPage()
})
AfterAll(async () => {
  await global.browser.close()
})

The above code Generates capabilities for BrowserStack using the caps() function from the ‘BrowserStack’ module. Construct the WebSocket endpoint URL for BrowserStack with the generated capabilities.

Now we have completed the BrowserStack implementation in our framework, now you can execute your tests on BrowserStack.

To execute tests on BrowserStack make sure you have “Browserstack = true” in the .env file.

Then you can execute your tests using the command ’npm run test’ on your terminal.

After running the test cases on BrowserStack, you’ll find the report below. Access comprehensive execution videos, and test logs for both successful and unsuccessful cases, along with execution duration.

Conclusion:

Integrating BrowserStack with Playwright JavaScript tests, gives access to a wide range of real browsers and devices, enabling comprehensive cross-browser and cross-platform testing. The scalability and cost-effectiveness of BrowserStack eliminate the need for maintaining an extensive device lab. Ultimately, this integration enhances test coverage, improves software quality, and ensures a seamless user experience across various browsers and platforms.

Read more blogs here

How to create a BDD automation framework using Cucumber in JavaScript and Playwright?

How to create a BDD automation framework using Cucumber in JavaScript and Playwright?

Introduction:

In this Blog will learn How to create a BDD automation framework using Cucumber in JavaScript and Playwright.
The playwright is an open-source automation tool. Playwright offers several features that make it stand out are Multi-browser support, Automatic waiting Headless and headful mode, etc.
Cucumber is a popular open-source BDD(Behavior Driven Development) testing framework, Which helps build a framework that can be easily understood by both technical and non-technical stakeholders.

Prerequisite:

To get started with Cucumber BDD with playwright-js we need to have the following things installed.

1)VS Code: We will use VS Code as IDE to write our test cases, to get this you can visit ‘https://code.visualstudio.com/download’.

2)Node.js: It is a cross-platform JavaScript runtime environment that allows developers to run JavaScript code outside of a web browser.
To get Node.js you can visit: https://nodejs.org/en/download
To check Node.js is installed on your system you can use the command ‘node –version’ on CMD or VS Code Terminal.

3)Cucumber (Gherkin) Full Support Extention: This extension provides support for the Cucumber (Gherkin) language to VS Code.
To get the extension click on the extension icon on the left side panel of VS Code, search for the extension and install it.

Project setup:

Before starting with framework development we need to create a folder structure.

Create a folder structure with the following steps:
1) Create a folder as ‘Playwright-JS-Demo’,
2) In VS Code open the Playwright-JS-Demo folder
3) Install Playwright and Cucumber by executing the following commands in terminal
a. npm init playwright@latest

b.npm i @cucumber/cucumber
After execution of these commands, you can see package.json, node_modules, and playwright.config.js is created in the folder structure.

4) once you open the project, create a folder structure as below.

As our project structure is ready, we can start with the framework.

1. TestHooks.js:

  • Test Hooks mainly contain methods to execute Before and After every execution.
  • The Before hook gets executed before each Scenario in a cucumber test suite.
  • In this hook, a new Chrome browser instance is launched for every Test Case.
  • A new page is created in context with ‘await context.newPage()‘ and assigned to the global variable ‘page‘, which is accessible for any Test Case. This ensures that the browser page is available for each scenario in the test suite. 
  • Once execution is done After the method gets executed It closes the current browser instance.
const { Before, AfterAll } = require('@cucumber/cucumber')
const page = require('@playwright/test')
Before(async () => {
  let browser = await page.chromium.launch({ headless: false })
  global.browser = browser
  const context = await browser.newContext()
  global.page = await context.newPage()
})
AfterAll(async () => {
  await global. browser.close()
})

2. Login.feature:

  • With Cucumber-BDD we can write scenarios in understandable language.
    Here I have created a Scenario for OrangeHRM Login.
  • We can create a separate scenario for each functionality.
  • Every step in a Feature File describes the action we are going to perform on UI.
  • In the feature file, we can add specific tags for scenarios or complete feature file ex. @login, @smoke.
  • If you add a tag for a specific scenario then it will only execute the particular scenario. But if you add tags for the Feature It will execute all the Scenarios from the Feature File.
  • It will make test execution easy if you want to execute test cases for specific functionality.
Feature: Login Feature
@login
Scenario: Login to OrangeHRM
 When I Visit the OrangeHRM login page
 And I enter username
 And I enter Password
 And I click on Login button
Then I verify dashboard URL

3. LoginSteps.js:

Essentially, the purpose of the step file is to attach steps from the feature file to the page file, where actual implementation is available.

We use the “Given-When-Then” (BDD) format to write step definitions.
The required statement imports the necessary modules like:

  • Cucumber library that contains definitions for When Then etc.
  • A custom LoginPage module that likely contains functions for interaction with the login page.

The steps with ‘When’ are related to the user actions like navigation, clicking on the button, and filling in the information in input boxes, etc.
The steps with ‘Then’ are related to the verifications or Assertions, just like in this case I have verified if the Login is successful.

const { When, Then } = require('@cucumber/cucumber')
const { LoginPage } = require('../page/LoginPage')
let loginPage = new LoginPage()
When('I Visit the OrangeHRM login page', async () => {
    await loginPage.navigate()
})
When('I enter username', async () => {
    await loginPage.enterUsername()
})
When('I enter Password', async () => {
    await loginPage.enterPassword()
})

When('I click on Login button', async () => {
   await loginPage.clickOnLoginButton()
})
Then('I verify dashboard URL', async () => {
    await loginPage.verifyDashboardURL()
})

4. LoginPage.js:

The page file contains the actual implementation of the scenario, We also defined all the functions needed for test execution.
Additionally, the LoginPage class contains functions that interact with the login page elements, like navigation to the Login page, entering the username and password, clicking the login button, and verifying the dashboard URL. Moreover, the playwright provides different functions to handle the UI elements and pages.
For this test case I have used goto(), click(), fill() waitFor().

process.env.WEB_URL, process.env.WEB_USERNAME and process.env.WEB_PASSWORD are the variables we are accessing from the .env file. (The use of the .env file is explained below in point no 6).

To access the .env file I have imported const path = require(‘path’);

const { expect } = require('@playwright/test')
const path = require('path');
require('dotenv').config({
    path: path.join(__dirname, '../.env'),
});
class LoginPage {
    async navigate() {
        await global.page.goto(process.env.WEB_URL)
    }
    async enterUsername() {
        await global.page.locator('//input[@placeholder="Username"]').waitFor({ status: 'visible' })
        await global.page.locator('//input[@placeholder="Username"]').fill(process.env.WEB_USERNAME)
    }
    async enterPassword() {
        await global.page.locator('//input[@placeholder="Password"]').fill(process.env.WEB_PASSWORD)
    }
    async clickOnLoginButton() {
        await global.page.locator('//button[@type="submit"]').click()
    }
    async verifyDashboardURL() {
       expect(await global.page.url()).toEqual('https://opensource-demo.orangehrmlive.com/web/index.php/dashboard/index')
    }
}
module.exports = { LoginPage }

5. Cucumber.json:

In this file, we specify the paths of all the required files. It helps to identify files in the framework.
Whenever you create any new file in the framework, you have to add a path for that new file in this Cucumber.json file so that it can be accessible during the test case execution.

{
    "default":{
        "require": [
            "steps/*.js",
            "page/*.js",
          "Utility/*.js"
        }
    }
}

6. .env:

.env file is a Configuration file that contains environment variables. Using a .env file is a best practice for keeping sensitive information separate from the code. Moreover, for this framework, we have stored information like URL to navigate and username and password to Login into the OrangeHRM Web application.

headless= false
WEB_URL= 'https://opensource-demo.orangehrmlive.com/web/index.php/auth/login'
WEB_USERNAME = 'Admin'
WEB_PASSWORD = 'admin123'

To execute the test case and get the report you will need to add the following command in a script tag of the package.json file

"scripts": 
{
    "test": "npx cucumber-js --require ./steps/*.js --tags @login --publish
}

We are executing the ‘npx’ command to run the cucumber-js package which is a test framework for BDD.
1) –require ./steps/*.js specifies The step files from the specified path that should be loaded.
2)–tags @login specifies scenarios with @login tags are going to be executed.
You can add more than one tag if needed.

3)–publish flag specifies that test results should be published to the Cucumber Cloud which is a service for storing and analyzing test results.

To start execution you can execute the command ‘npm run test’ in the terminal.
Once execution is completed you can see the link for cucumber reports is available in the terminal. By clicking on this link you can see the execution report.

This is how the report looks when you click on the above URL

Now as we have the framework ready, I have added this framework to the following Git Repository.
https://github.com/spurqlabs/Playwright_JS_BDD_Framework

Conclusion:

In conclusion, the BDD automation framework using Cucumber in JavaScript and Playwright helps improve the quality and efficiency of their testing process.
This framework will help you to write test cases for any web application very efficiently, It also provides a great reusability of code.

Read more blogs here.

API Test Automation using Playwright and Java

API Test Automation using Playwright and Java

 Most of us are familiar with API testing tools like Postman, SoapUI, etc, and API automation libraries like RestAssured and Karate to automate API test cases. A recent entrant in this category is Playwright. The playwright is an Automation Tool provided by Microsoft. It provides cross-browser testing using which we can perform testing on multiple browsers like Chromium, Webkit, Firefox, etc. playwright supports cross-language testing (Java, Node.js, Python, .NET, etc.). However, very few of us know that it can actually do an API Test automation of methods GET, PUT, POST, and DELETE. Let’s see how it can be done.

Can we perform API testing using Playwright?

The playwright provides inbuilt support for API testing that’s why we don’t need any external libraries to handle API. The playwright doesn’t use any browser to call API. It sends requests using Node.js which provides faster execution.

In this tutorial, we will explore basic API methods with the help of Playwright- java. Below are the Four methods.

  1. GET
  2. POST
  3. PUT
  4. DELETE

Pre-requisite:

To get started with API automation with playwright-java first we need playwright to be installed in your system, to do this we can simply add the following dependency in the pom.xml file.

Along with the playwright, we have to add Testing and JSON dependencies.

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.23.0</version>
</dependency>

<dependency>
   <groupId>org.testng</groupId>
   <artifactId>testng</artifactId>
   <version>7.1.0</version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>com.googlecode.json-simple</groupId>
   <artifactId>json-simple</artifactId>
   <version>1.1.1</version>
</dependency>

Now let’s see how we can start API automation testing with Playwright-java.

1. GET:

By providing an API endpoint we can read data using a GET request. We must pass a few parameters to get the required data from the API.

We can verify the request by asserting the Response Code. The response code for a successful GET Request is 200. You can also assert a text inside the JSON body response.          

For Example, I am using postman here to send a GET request to ”  ‘/api/users/4’ endpoint of a sample API URL ‘https://reqres.in’

The below code shows the implementation of the GET method through Playwright.

@Test
public void get() throws IOException, ParseException {
   Playwright playwright = Playwright.create();
   String BaseURL="https://reqres.in";
   Map<String, String> headers = new HashMap<>();
   headers.put("content-type", "application/json");
   APIRequestContext apiRequestContext= playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL).setExtraHTTPHeaders(headers));
   APIResponse response = apiRequestContext.get("/api/users/4");
   int responseCode=response.status();
   Assert.assertEquals(responseCode,200);

   String responseText= response.text();
   JSONParser j= new JSONParser();
   JSONObject json = (JSONObject) j.parse(responseText);

   String responseData= json.get("data").toString();
   JSONObject jsonData = (JSONObject) j.parse(responseData);
   Assert.assertEquals(jsonData.get("email"),"eve.holt@reqres.in");
   Assert.assertEquals(jsonData.get("first_name"), "Eve");
   Assert.assertEquals(jsonData.get("last_name"), "Holt");
   Assert.assertEquals(jsonData.get("avatar"), "https://reqres.in/img/faces/4-image.jpg");
   apiRequestContext.dispose();
   playwright.close();
}

To verify the response data we are parsing the response to JSON Object so that we can verify specific key-value pairs.

2. POST:

POST method is used to add a new record via API where we have to pass data as payload ex. first name, last name, etc. The response code for a successful POST Request is 201.

For example, I am sending a POST request to  ‘/api/users/’ endpoint with base URL ‘https://reqres.in‘ and the body as given below in the screenshot:

To pass the data payloads to the POST/PUT method, first, we have to create a POJO class which will help to create methods to get and set payloads.
below we have created a POJO class employee which will help to get and set data to both POST and PUT calls.

public class Employee {
// private variables or data members of pojo class
private String email;
private String first_name;
private String last_name;
private String avatar;

public String getEmail() {
   return email;
}
public void setEmail(String email) {
   this.email = email;
}
public String getFirstName() {
   return first_name;
}
public void setFirstName(String firstName) {
   this.first_name = firstName;
}
public String getLastName() {
   return last_name;
}
public void setLastName(String lastName) {
   this.last_name = lastName;
}
public String getAvatar() {
   return avatar;
}
public void setAvatar(String avatar) {
   this.avatar = avatar;
}
}

The below code will help you with the POST method through Playwright.

@Test
public void post() throws ParseException {
   employee employee = new employee();
   employee.setEmail("john@reqres.in");
   employee.setFirstName("john");
   employee.setLastName("Holt");
   employee.setAvatar("https://reqres.in/img/faces/4-image.jpg");

   Playwright playwright = Playwright.create();
   String BaseURL = "https://reqres.in";
   Map<String, String> headers = new HashMap<>();
   headers.put("content-type", "application/json");
   APIRequestContext apiRequestContext = playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL).setExtraHTTPHeaders(headers));
   APIResponse response = apiRequestContext.post("/api/users/", RequestOptions.create().setData(employee));

   Assert.assertEquals(response.status(),201);
   String responseText= response.text();
   JSONParser j= new JSONParser();
   JSONObject json = (JSONObject) j.parse(responseText);
   Assert.assertEquals(json.get("email"), employee.getEmail());
   Assert.assertEquals(json.get("first_name"), employee.getFirstName());
   Assert.assertEquals(json.get("last_name"), employee.getLastName());
   Assert.assertEquals(json.get("avatar"), employee.getAvatar());
   apiRequestContext.dispose();
   playwright.close();
}

3. PUT:

PUT Request is used to update the existing records via the API. we have to pass the data we want to update as a payload ex. first name, last name, etc. The response code for a successful PUT Request is 200.

For example, I am sending a POST request to ‘/api/users/55’ endpoint with the base URL ‘https://reqres.in’ and the body as given below in the screenshot:

The below example shows the implementation of the PUT method. We need to use the above POJO class to pass the data as a payload to the PUT call.

 @Test
public void put() throws ParseException {
   employee employee = new employee();
   employee.setEmail("john@reqres.in");
   employee.setFirstName("Harry");
   employee.setLastName("Eve");
   employee.setAvatar("https://reqres.in/img/faces/4-image.jpg");

   Playwright playwright = Playwright.create();
   String BaseURL = "https://reqres.in";
   Map<String, String> headers = new HashMap<>();
   headers.put("content-type", "application/json");
   APIRequestContext apiRequestContext = playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL).setExtraHTTPHeaders(headers));
   APIResponse response = apiRequestContext.put("/api/users/55", RequestOptions.create().setData(employee));

   Assert.assertEquals(response.status(),200);
   String responseText= response.text();
   JSONParser j= new JSONParser();
   JSONObject json = (JSONObject) j.parse(responseText);
   Assert.assertEquals(json.get("email"), employee.getEmail());
   Assert.assertEquals(json.get("first_name"), employee.getFirstName());
   Assert.assertEquals(json.get("last_name"), employee.getLastName());
   Assert.assertEquals(json.get("avatar"), employee.getAvatar());
}

4 DELETE:

We can delete existing records using the API by using DELETE Request. Ideally, you must have added a record before you delete it. Hence you would need to append an ID to the DELETE URL. To delete the record using API first we need to pass the record URI (Universal Resource Identifier). The response code for a successful DELETE Request is 200.

For example, I am sending a POST request to ‘https://retoolapi.dev’ endpoint with base URL ‘/3njSPM/calc/43’ and the body as given below in the screenshot:

Following is the code for the DELETE method in Playwright

@Test
public void delete()  {
   Playwright playwright = Playwright.create();
   String BaseURL = "https://retoolapi.dev";
   APIRequestContext apiRequestContext = playwright.request().newContext(new APIRequest.NewContextOptions()
           .setBaseURL(BaseURL));
   APIResponse response = apiRequestContext.delete("/3njSPM/calc/40");
   int responseCode = response.status();
   Assert.assertEquals(responseCode, 200);
   Assert.assertEquals(response.statusText(), "OK");
   apiRequestContext.dispose();
   playwright.close();

 

After performing a DELETE call we can perform a GET call on the same endpoint to verify data is actually deleted. For this GET call, we will get response code 204 as the content is not found.

For Reference: https://playwright.dev/java/docs/api-testing

Conclusion:-

GET, PUT, POST, and DELETE are the basic CRUD API methods used in any Web application. With the help of the inbuilt functionalities of Playwright, API Automation Testing became much easier and faster.

Read more blogs here