Page Object Model without Page Factory in Selenium Webdriver

HOME

What is Page Object Model?

Page Object Model(POM) is an object design pattern in Selenium webdriver which tells how to organize the object repository. In this case, we refer to web elements as Objects. Page Object Model(POM) is not a Test Framework.

In the Page Object Model (POM), each web page is represented as a separate class. For example, consider HRM website. It has many web pages like Login , Dashboard , Assign Leave, Leave List, Timesheets, etc. Under this model, for each web page in the application, there should be a corresponding Page Class. This Page class will identify the WebElements of that web page and also contains Page methods that perform operations on those WebElements.

If a new web element is added or an existing web element is updated, then you can add or update that web element in object repository by navigating to class which has same name as webpage.

The object repository is independent of test cases, so we can use the same object repository for a different purpose with different tools. For example, we can integrate Page Object Model in Selenium with TestNG/JUnit for functional Testing and at the same time with JBehave/Cucumber for acceptance testing.

POM enhances test maintenance, readability and reducing code duplication.

In this tutorial, I’m creating a project using Page Object Model as Design Pattern and TestNG as the Test Automation Framework.

Steps to create a Page Object Model Project

  1. Download and Install Java on system
  2. Download and setup Eclipse IDE on system
  3. Setup Maven
  4. Create a new Maven Project
  5. Add dependencies to pom.xml
  6. Create Page Class for each page – LoginPage.Java and DashboardPage.java
  7. Create tests for each Page – BaseTests, LoginTests and DashboardTests
  8. Create a TestNG.XML
  9. Run the tests from TestNG.xml
  10. TestNG Report Generation

Step 1- Download and Install Java

Click here to know How to install Java. To check if Java is already installed on your machine, use the below 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 system

The Eclipse IDE (integrated development environment) provides strong support for Java developer. The Eclipse IDE for Java Developers distribution is designed to support standard Java development. It includes support for the Maven and Gradle build system and support for the Git version control system. Click here to know How to install Eclipse.

Step 3 – Setup Maven

To build a test framework, we need to add a number of dependencies to the project. It is 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 which is used to define project structure, dependencies, build, and test management. Click here to know How to install Maven.

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

mvn -version

Step 4 – Create a new Maven Project

Click here to know How to create a Maven project

Below is the Maven project structure. Here,

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

Step 5 – Add dependencies to the pom.xml

I have added Selenium and TestNG dependencies.

<dependencies>
  
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.4.0</version>
      <scope>test</scope>
    </dependency>   
    
</dependencies>

Step 6 – Create Page Class for each page – LoginPage.Java and DashboardPage.java

I want to test 2 pages – Login and Dashboard. So, I’m creating 2 seperate class. Each class will contain its web elements and methods of that page.

LoginPage.Java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {

	WebDriver driver;

	By userName = By.name("txtUsername");

	By password = By.name("txtPassword");

	By titleText = By.id("logInPanelHeading");

	By login = By.id("btnLogin");

	public LoginPage(WebDriver driver) {
		this.driver = driver;
	}

	// Set user name in textbox
	public void setUserName(String strUserName) {
		driver.findElement(userName).sendKeys(strUserName);
	}

	// Set password in password textbox
	public void setPassword(String strPassword) {
		driver.findElement(password).sendKeys(strPassword);
	}

	// Click on login button
	public void clickLogin() {
		driver.findElement(login).click();
	}

	// Get the title of Login Page
	public String getLoginTitle() {
		return driver.findElement(titleText).getText();
	}

	public void login(String strUserName, String strPasword) {

		// Fill user name
		this.setUserName(strUserName);

		// Fill password
		this.setPassword(strPasword);

		// Click Login button
		this.clickLogin();
	}
}

DashboardPage.java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class DashboardPage {

	WebDriver driver;

	By homePageUserName = By.id("welcome");

	public DashboardPage(WebDriver driver) {
		this.driver = driver;

	}

	// Get the User name from Home Page
	public String getHomePageText() {
		return driver.findElement(homePageUserName).getText();
	}

}

Step 7 – Create tests for each Page – BaseTests, LoginTests and DashboardTests

Here, I have created 3 classes. BaseTest class to contain startUp and tearDown methods. These methods will run once before the after of every class. LoginTests and DashboardTests classes contain the tests related to LoginPage and DashboardPage respectively.

BaseTest

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

import com.example.pageobjectmodel_demo.pages.DashboardPage;
import com.example.pageobjectmodel_demo.pages.LoginPage;

public class BaseTest {

	public static WebDriver driver;
	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@BeforeClass
	public void setup() {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.get("https://opensource-demo.orangehrmlive.com/");
	}

	@AfterClass
	public void close() {
		driver.close();
	}
}

LoginTests

import org.testng.Assert;
import org.testng.annotations.Test;

import com.example.pageobjectmodel_demo.pages.DashboardPage;
import com.example.pageobjectmodel_demo.pages.LoginPage;

public class LoginTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Test(priority = 0)
	public void loginTest() {

		// Create Login Page object
		objLogin = new LoginPage(driver);

		// Verify login page text
		String loginPageTitle = objLogin.getLoginTitle();
		Assert.assertTrue(loginPageTitle.contains("LOGIN Panel"));
	}

}

DashboardTests

import org.testng.Assert;
import org.testng.annotations.Test;

import com.example.pageobjectmodel_demo.pages.DashboardPage;
import com.example.pageobjectmodel_demo.pages.LoginPage;

public class DashboardTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Test(priority = 0)
	public void DasboardTest() {

		objLogin = new LoginPage(driver);

		// login to application
		objLogin.login("Admin", "admin123");

		// go the dashboard page
		objDashboardPage = new DashboardPage(driver);

		// Verify dashboard page
		Assert.assertTrue(objDashboardPage.getHomePageText().contains("Welcome"));
	}

}

Step 8 – Create a TestNG.XML

Here, I have mentioned 2 test classes. So, when I will run the tests from TestNG.xml, it will run the tests of both the classes. If will mention any one class, then the test of that particular class will be executed.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "PageObjectModel">
  <test name = "PageObjectModel Tests">
    <classes>
          <class name = "com.example.pageobjectmodel_demo.tests.LoginTests"/>
          <class name = "com.example.pageobjectmodel_demo.tests.DashboardTests"/>
     </classes>  
   </test>
</suite>

Step 9 – Run the tests from TestNG.xml

Right click on TestNG.xml and select Run As TestNG Suite.

The execution status looks like as shown below.

Step 10 – TestNG Report Generation

Once the execution is finished, refresh the project. It will create a test-output folder containing various reports generated by TestNG. Below is the screenshot of the report folder.

Image of Index.html report

Image of emailable-report.html

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

Integration of Selenium with TestNG

HOME

In this tutorial, I’ll create a Framework for the testing of web applications using Selenium Webdriver with TestNG . This framework consists of:-

  1. Selenium
  2. Java 8 or above
  3. TestNG
  4. Maven

Steps to setup Cucumber Test Automation Framework with Selenium and TestNG

  1. Download and Install Java on system
  2. Download and setup Eclipse IDE on system
  3. Setup Maven
  4. Create a new Maven Project
  5. Add Selenium and TestNG dependencies to the project
  6. Create a Test file under src/test/java
  7. Run the tests from TestNG.xml
  8. TestNG Report Generation

Detailed Step Description

Step 1- Download and Install Java

Cucumber and Selenium needs Java to be installed on the system to run the tests. Click here to know How to install Java.

Step 2 – Download and setup Eclipse IDE on system

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

Step 3 – Setup Maven

To build a test framework, we need to add a number of dependencies to the project. It is 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 which is used to define project structure, dependencies, build, and test management. Click here to know How to install Maven.

Step 4 – Create a new Maven Project

Click here to know How to create a Maven project

Below is the Maven project structure. Here,

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

Step 5 – Add Selenium and TestNG dependencies to the project.

As this is a Maven project, we can add the dependencies in POM.xml as shown below.

 <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>
    
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.4.0</version>
      <scope>test</scope>
    </dependency>


<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core -->
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest</artifactId>
      <version>2.2</version>
      <scope>test</scope>
    </dependency>

After addition of dependencies in pom.xml, Maven Dependencies folder will be updated automatically with all the JAR file related to the dependencies.

Step 6 – Create a Test file under src/test/java

@BeforeTest – methods under this annotation will be executed prior to the first test case in the TestNG file.

@AfterTest – methods under this annotation will be executed after all test cases in the TestNG file are executed.

@Test – The annotated method is a part of a test case.

Description –  You can describe your test case under the description, stating what it does.

description = "This test validates title of login functionality"

Priority – You can prioritize the order of your test methods by defining a priority. Based on the defined priority, the test shall execute in that order.

priority = 0
public class TestNG_Demo {

	WebDriver driver;

	@BeforeTest
	public void setUp() {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");

		driver = new FirefoxDriver();
		driver.get("https://opensource-demo.orangehrmlive.com/");

		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Test(description = "This test validates title of login functionality", priority = 0)
	public void verifyLoginPage() {

		String expectedTitle = driver.findElement(By.xpath("//*[@id='logInPanelHeading']")).getText();

		System.out.println("Title :" + expectedTitle);
		assertTrue(expectedTitle.equalsIgnoreCase("LOGIN Panel"));
	}

	@Test(description = "This test validates  successful login to Home page", priority = 1)
	public void verifyHomePage() {

		System.out.println("Username Entered");
		driver.findElement(By.name("txtUsername")).sendKeys("Admin");

		System.out.println("Password Entered");
		driver.findElement(By.name("txtPassword")).sendKeys("admin123");

		driver.findElement(By.id("btnLogin")).submit();

		String newPageText = driver.findElement(By.id("welcome")).getText();
		System.out.println("newPageText :" + newPageText);
		assertThat(newPageText, containsString("Welcome"));
	}

	@AfterTest
	public void teardown() {

		driver.quit();
	}

}

Step 7 – Test Execution through TestNG

Go to Runner class and right click Run As TestNG Test. The tests will run as TestNG tests.

Step 8 – Run the tests from TestNG.xml

Create a TestNG.xml as shown below and run the tests as TestNG.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
  <test name = "TestNG Demo">
    <classes>
          <class name = "com.example.Selenium_TestNGDemo.TestNG_Demo"/>
     </classes>  
   </test>
</suite>

Step 9 – TestNG Report Generation

TestNG generates various type of reports under test-output folder like emailable-report.html, index.html, testng-results.xml.

We are interested in ’emailable-report.html’ report. Open ’emailable-report.html’, as this is a html report open it with browser. Below image shows emailable-report.html.

TestNG also produce “index.html” report and it resides under test-output folder. Below image shows index.html report. This is the latest theme of the report.

The links present at the left side are clickable. I have clicked Times link and you can see the details on the right side.

isDisplayed, isSelected, isEnabled in Selenium

HOME

This tutorial describes how to check the state of a WebElement.

In this tutorial, we will learn isDisplayed, isEnabled, isSelected method in Selenium, and how to check the state of a WebElement. There are many methods which are used to determine the visibility scope for the web elements – isSelected(), isEnabled() and isDispalyed().

Many a time a test fails when we click on an element or enter text in a field. This is because the element is displayed or exist in DOM, but it does not exist on the web page.

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

  • isDisplayed()
  • isSelected()
  • isEnabled()
  1. Boolean isSelected(): This method determines if an element is selected or not. It returns true if the element is selected and false if it is not. It is widely used on check boxes, radio buttons and options in a select.

2. Boolean isDisplayed(): This method determines if an element is displayed or not. It returns true if the element is displayed and false if it is not. Advantage of this method is that it avoids parsing an elements style attribute.

3. Boolean isEnabled(): This method determines if an element is enabled or not. It returns true if element is enabled (All elements apart from disabled input elements) and false if otherwise.

Steps to follow to understand when an element isEnabled and isDisplayed.

  1. Launch the web browser and open the application under test – https://duckduckgo.com/
  2. Verify the web page title
  3. Verify if the “Search Box” is displayed
  4. Verify that the “Search Box” is enabled
  5. If Search Box is enabled, then search for text – Selenium
  6. Close the browser
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class VerifyConditionsDemo {

	public static void main(String[] args) {

		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");
		
WebDriver driver = new FirefoxDriver();

		// launch the firefox browser and open the application url
		driver.get("https://duckduckgo.com/");

		// maximize the browser window
		driver.manage().window().maximize();

		// declare and initialize the variable to store the expected title of the
		// webpage.
		String expectedTitle = "DuckDuckGo — Privacy, simplified.";

		// fetch the title of the web page and save it into a string variable
		String actualTitle = driver.getTitle();

		// compare the expected title of the page with the actual title of the page and
		// print the result
		if (expectedTitle.equals(actualTitle)) {
			System.out.println("Verification Pass- The correct title is displayed on the web page.");
		} else {
			System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
		}

		// verify that the “Search" Box is displayed
		WebElement searchBox = driver.findElement(By.id("search_form_input_homepage"));
		if (searchBox.isDisplayed()) {
			System.out.println("Search Box is visible. Return: " + searchBox.isDisplayed());
		} else {
			System.out.println("Search Box is not visible. Return: " + searchBox.isDisplayed());
		}

		// verify that the “Search” Box is enabled
		if (searchBox.isEnabled()) {
			System.out.println("Search Box is enabled. Return: " + searchBox.isEnabled());
			searchBox.sendKeys("Selenium");
		} else {
			System.out.println("Search Box is not enabled. Return: " + searchBox.isEnabled());
		}

		System.out.println("Successful Execution of Test.");

		// close the web browser
		driver.close();

	}
}

Output
Verification Pass- The correct title is displayed on the web page.
Search Box is visible. Return: true
Search Box is enabled. Return: true
Successfull Execution of Test.

isSelected

Steps to follow to understand when an element is Selected or not.

  1. Launch the web browser and open the application under test – https://www.seleniumeasy.com/test/basic-radiobutton-demo.html
  2. Verify if first Radio Button (Male) is selected or not
  3. If first radio button is already selected, then select Radio Button 2, else vice versa.
  4. Print the value of selected Radio Button
  5. Print the value of selecting a Radio Button
  6. Close the browser

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class isSelectedDemo {

	public static void main(String[] args) {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");

		FirefoxDriver driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		driver.get("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html");

		List<WebElement> Radio_Options = driver.findElements(By.name("optradio"));

		// Create a boolean variable which will hold the value (True/False)
		boolean radio_value = false;

		// This statement will return True, in case of first Radio button is selected
		radio_value = Radio_Options.get(0).isSelected();

		// Identify if Radio Button 1 is selected or not. If Button 1 is already
		// selected, then select Button 2
		if (radio_value == true) {
			Radio_Options.get(1).click();
			System.out.println("Button Selected is :" + Radio_Options.get(1).getAttribute("value"));
		} else {
			Radio_Options.get(0).click();
			System.out.println("Button Selected is :" + Radio_Options.get(0).getAttribute("value"));
		}

		driver.findElement(By.id("buttoncheck")).click();
		String Button_Selected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]"))
				.getText();
		System.out.println("Get Checked Value is :" + Button_Selected);

		// close the web browser
		driver.close();
	}
}

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

How to write data in Excel in Java

HOME

This tutorial describes the steps to write data in Excel file in Java.

I’m using Apache POI to write data to the excel file. To download and install Apache POI, refer here.

In the previous tutorial, I have explained How to read data from Excel in Java.

Dependency:

If you are using maven, then you need to add below dependency in pom.xml.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>
 
 
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

Here are few classes which you need to aware of.

  • Workbook : This is high level class for representing excel workbook.
  • Sheet : This is high level class for representing excel sheet.
  • Row : This is high level class for representing excel row. It has methods which are related to row.
  • Cell: This is high level class for representing individual excel cell. It has methods which are related to cell for example : getDataType().

The basic steps for writing data into an excel file using Apache POI API are given below:

Step 1 – Create a blank workbook.

XSSFWorkbook wb = new XSSFWorkbook();

Step 2 – Import XSSFWorkbook from package.

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Step 3 – Create a sheet and pass name of the sheet.

XSSFSheet sheet = workbook.createSheet("Write_TestData");

Step 4 – Import XSSFSheet from package.

import org.apache.poi.xssf.usermodel.XSSFSheet;

Step 5 – Create a Row. A spreadsheet consists of rows and cells. It has a grid layout.

 XSSFRow row = sheet.createRow(rownum++);

Step 6 – Import XSSFRow from package

import org.apache.poi.xssf.usermodel.XSSFRow;

Step 7 – Create cells in a row. A row is a collection of cells. When you enter data in the sheet, it is always stored in the cell.

 XSSFCell cell = row.createCell(cellnum++);

Step 8 – Import XSSFCell from package.

 XSSFCell cell = row.createCell(cellnum++);

Step 9 – Write data to an OutputStream. Use the below code to write output stream.

FileOutputStream out = new FileOutputStream(new File("EmployeeDetails.xlsx"));
workbook.write(out);

Step 10 – Close the output stream.

out.close();

Below is the entire code for writing the data in an excel in Java.

package com.example.seleniumdemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

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;

public class ReadWriteExcelFile {

	public static void main(String[] args) throws IOException {

		// create blank workbook
		XSSFWorkbook workbook = new XSSFWorkbook();

		// Create a blank sheet
		XSSFSheet sheet = workbook.createSheet("Write_TestData");

		ArrayList<Object[]> data = new ArrayList<Object[]>();
		data.add(new String[] { "Name", "Id", "Salary" });
		data.add(new Object[] { "Jim", "001A", 10000 });
		data.add(new Object[] { "Jack", "1001B", 40000 });
		data.add(new Object[] { "Tim", "2001C", 20000 });
		data.add(new Object[] { "Gina", "1004S", 30000 });

		// Iterate over data and write to sheet
		int rownum = 0;
		for (Object[] employeeDetails : data) {

			// Create Row
			XSSFRow row = sheet.createRow(rownum++);

			int cellnum = 0;
			for (Object obj : employeeDetails) {

				// Create cell
				XSSFCell cell = row.createCell(cellnum++);

				// Set value to cell
				if (obj instanceof String)
					cell.setCellValue((String) obj);
				else if (obj instanceof Double)
					cell.setCellValue((Double) obj);
				else if (obj instanceof Integer)
					cell.setCellValue((Integer) obj);
			}
		}
		try {

			// Write the workbook in file system
			FileOutputStream out = new FileOutputStream(new File("EmployeeDetails.xlsx"));
			workbook.write(out);
			out.close();
			System.out.println("EmployeeDetails.xlsx has been created successfully");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			workbook.close();
		}
	}

}

That’s it! We have written data in Excel.

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

How to read data from Excel in Java

HOME

This tutorial describes to read data from Excel file in Java.

I’m using Apache POI to read the excel file. To download and install Apache POI, refer here.

The two mainly used  classes for managing Excel Workbooks are:

  • HSSFWorkbook- These class methods are used to read/write data to Microsoft Excel file in .xls format. It is compatible with MS-Office versions 97–2003.
  • XSSFWorkbook- These class methods are used to read-write data to Microsoft Excel in .xls or .xlsx format. It is compatible with MS-Office versions 2007 or later.

How to read Excel (.xlsx) from specific cell value?

Step 1 – To locate the location of file.

File file = new File("C:\\Selenium_ReadTestData.xlsx");

Import File from package

import java.io.File;

Step 2 – Instantiate FileInputStream to read from the file specified.

 FileInputStream fis = new FileInputStream(file);

Step 3 – Create object of XSSFWorkbook class

XSSFWorkbook wb = new XSSFWorkbook(fis);

Step 4 –  Import XSSFWorkbook from package

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Step 5 – To read excel sheet by sheet name

XSSFSheet sheet1 = wb.getSheet("Read_TestData");

Step 6 – Import XSSFSheetfrom package

import org.apache.poi.xssf.usermodel.XSSFSheet;

Step 7 –  To access data from the XLSX file, use of  the following methods:

getRow(int rownum)
getCell(int cellnum)
getStringCellValue()
getNumericCellValue()

Step 8 –  To get the cell value from column A and Row 1

 System.out.println(sheet1.getRow(0).getCell(0).getStringCellValue());

Here getRow(0) will look into the first row, and getCell(0) will look into the first column, i.e. A1.

To retrieve the String value we are making use of getStringCellValue in the end.

Below is the Excel which I’m using to read the data as mentioned below:-

We want to get the value of Row 1, Cell B

We want to get the value of Row 3, Cell A

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

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadSpecificData {

	public static void main(String[] args) {
		
     String path = "C:\\Selenium_ReadTestData.xlsx";	

		try {
			
			//Create an object of FileInputStream class to read excel file
			FileInputStream fis = new FileInputStream(path);
			
			//Create object of XSSFWorkbook class
			XSSFWorkbook wb = new XSSFWorkbook(fis);
			
			//Read excel sheet by sheet name 
			XSSFSheet sheet1 = wb.getSheet("Read_TestData");
			
			//Get data from specified cell
			System.out.println(sheet1.getRow(1).getCell(1).getStringCellValue());
			System.out.println(sheet1.getRow(3).getCell(0).getStringCellValue());
			
		} catch (IOException e) {
			e.printStackTrace();
		}	

	}

}

Output
Tom
302AC

How to read the entire Excel sheet?

To read the complete data from Excel, you can iterate over each cell of the row, present in the sheet. 

To get the last and first-row number, there are two methods in the sheet  class:

  • getLastRowNum() 
  • getFirstRowNum()
   int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();	  

Once you get the row, you can iterate over the cells present in the row by using the total number of cells, that we can calculate using getLastCellNum() method:

int cellcount=sheet.getRow(1).getLastCellNum();

Below is the entire program to read complete excel.

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

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelFile {
	public static  void main(String args[]) throws IOException {
		
		String path = "C:\\Selenium_ReadTestData.xlsx";
		
		//Create an object of FileInputStream class to read excel file
		FileInputStream fis = new FileInputStream(path);
		
		//Create object of XSSFWorkbook class
		Workbook workbook = new XSSFWorkbook(fis);
		
		//Read excel sheet by sheet name 
		Sheet sheet = workbook.getSheet("Read_TestData");
		
		
		//Find number of rows in excel file
	    int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();	    
	    System.out.println("row count:"+rowCount);
		
		 //iterate over all the row to print the data present in each cell.
	    for(int i=0;i<=rowCount;i++){
	        
	        //get cell count in a row
	        int cellcount=sheet.getRow(i).getLastCellNum();	        
	   
	        //iterate over each cell to print its value       
	        for(int j=0;j<cellcount;j++){
	            System.out.print(sheet.getRow(i).getCell(j).getStringCellValue().toString() +"||");
	        }
	        System.out.println();
		}
	}
}

That’s it! We are done.

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

Page Object Model with Page Factory in Selenium

HOME

What Is Page Object Model (POM)?

Page Object model is an object design pattern in Selenium, where web pages are represented as classes, and the various elements on the page are defined as variables in the class and all possible user interactions can then be implemented as methods in the class.

The benefit is that if there is any change in the UI for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently all changes to support that new UI are located in one place.

The Page Object Design Pattern provides the following advantages:

1. Readable – There is a clean separation between test code and page specific code such as locators and methods.

2. Maintainability  -In this model, separate classes are created for different pages of a web application like login page, the home page, employee detail page, change password page, etc. So, if there is any change in any element of a website then we only need to make changes in one class, and not in all classes.

3. Reusable – If multiple test scripts use the same web elements, then we need not write code to handle the web element in every test script. Placing it in a separate page class makes it reusable by making it accessible by any test script.

4. Easy project Structure – Its project structure is quite easy and understandable.

5. PageFactory – It can use PageFactory in the page object model in order to initialize the web element and store elements in the cache.

In case there are lots of web elements on a page, then the object repository class for a page can be separated from the class that includes methods for the corresponding page.

 Example: If the New Customer page has many input fields. In that case, there can be 2 different classes. One class called NewCustomerObjects.java that forms the object repository for the UI elements on the register accounts page.

A separate class file NewCustomerMethods.java extending or inheriting NewCustomerObjects that includes all the methods performing different actions on the page could be created.

Consider the below script to login to an application and navigate to home page.

This is a small script. Therefore, script maintenance and readability looks very easy.

Imagine there are 50 different tests present in this script. In that case, the readability of the script decreases as well as maintenance become very difficult.

Scenario

  1. Launch the Firefox browser.
  2. The demo website opens in the browser.
  3. Verify the Login Page
  4. Enter username and Password and login to the demo site.
  5. Verify the home page.
  6. Close the browser.
package PageObjectModel;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class NonPOMExample {

     WebDriver driver;

     @BeforeTest
     public void setup() {

           System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
           driver = new FirefoxDriver();
           driver.manage().window().maximize();
           driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
           driver.get("https://opensource-demo.orangehrmlive.com/");
     }

     @Test(priority = 0)
     public void Login() {
           String pageTitle = driver.findElement(By.id("logInPanelHeading")).getText();
           Assert.assertTrue(pageTitle.contains("LOGIN Panel"));
     }

     @Test(priority = 1)
     public void HomePage() {

           driver.findElement(By.name("txtUsername")).sendKeys("Admin");
           driver.findElement(By.name("txtPassword")).sendKeys("admin123");
           driver.findElement(By.id("btnLogin")).submit();
           String homePageText = driver.findElement(By.id("welcome")).getText();
           Assert.assertTrue(homePageText.contains("Welcome"));
     }

     @AfterTest
     public void close() {
           driver.close();
     } 
}

What Is Pagefactory?

PageFactory is a way of implementing the “Page Object Model”. Here, we follow the principle of separation of Page Object Repository and Test Methods. It is an inbuilt concept of Page Object Model which is very optimized.

1. The annotation @FindBy is used in Pagefactory to identify an element while POM without Pagefactory uses the driver.findElement() method to locate an element.

2. The second statement for Pagefactory after @FindBy is assigning an <element name> of type WebElement class that works exactly similar to the assignment of an element name of type WebElement class as a return type of the method driver.findElement() that is used in usual POM (userName in this example).

Non POM

driver.findElement(By.name("txtUsername"));

POM

@FindBy(name = "txtUsername")
WebElement userName;

3. Below is a code snippet of non PageFactory Mode to set Firefox driver path. A WebDriver instance is created with the name driver and the FirefoxDriver is assigned to the ‘driver’.  The same driver object is then used to launch the demo website, locate the webelements and to perform various operations

Basically, here the driver instance is created initially and every web element is freshly initialized each time when there is a call to that web element using driver.findElement() or driver.findElements().

 System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
          driver = new FirefoxDriver();
           driver.manage().window().maximize();
           driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
           driver.get("https://opensource-demo.orangehrmlive.com/");

But with POM with PageFactory approach, all the elements are initialized with initElements() without explicitly initializing each web element.

The initElements is a static method of PageFactory class which is used to initialize all the web elements located by @FindBy annotation. Thus, instantiating the Page classes easily. It is used to initialize the WebElements declared, using driver instance from the main class. In other words, WebElements are created using the driver instance. Only after the WebElements are initialized, they can be used in the methods to perform actions.

public Login(WebDriver driver) {
           this.driver = driver;
           // This initElements method will create all WebElements
           PageFactory.initElements(driver, this);
     }

Steps To Create POM With Page Factory Real-Time Example

Step 1 – Create a Maven Project

Click here to know How to create a Maven project

Step 2 – Add dependencies to the pom.xml

<dependencies>
   
   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
    </dependency>
     
    <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>7.4.0</version>
      <scope>test</scope>
    </dependency>   
     
</dependencies>

Step 3 – Create a Java Class for each page:

In this example, we will access 2 web pages, “Login” and “Home” pages.

Hence, we will create 2 Java classes in Page Layer  –  Login.java and HomePage.java

3.1. Define WebElements as variables using Annotation @FindBy:

We would be interacting with:

  • Message on Login Page, Username, Password, Login button field on the Login Page.
  • Successful message on the Home Page

For Example: If we are going to identify the Username using attribute name, then its variable declaration is

 @FindBy(name = "txtUsername")
 WebElement userName;

3.2 Create methods for actions performed on WebElements.

Below actions are performed on WebElements in Login Page:

  • Get Text on Login Page
  • Type action on the Username field.
  • Type action in the Password field.
  • Click action on the Login Button

Note: A constructor has to be created in each of the class in the Page Layer, in order to get the driver instance from the Main class in Test Layer and also to initialize WebElements(Page Objects) declared in the page class using PageFactory.InitElement().

Login Page

package PageObjectModel;

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

public class Login {

     /**
      *
      * All WebElements are identified by @FindBy annotation
      *
      */
     WebDriver driver;

     @FindBy(name = "txtUsername")
     WebElement userName;

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

     @FindBy(id = "logInPanelHeading")
     WebElement titleText;

     @FindBy(id = "btnLogin")
     WebElement login;

     public Login(WebDriver driver) {
           this.driver = driver;

           // This initElements method will create all WebElements
           PageFactory.initElements(driver, this);
     }

     // Set user name in textbox
     public void setUserName(String strUserName) {
           userName.sendKeys(strUserName);
     }

     // Set password in password textbox
     public void setPassword(String strPassword) {
           password.sendKeys(strPassword);
     }

     // Click on login button
     public void clickLogin() {
           login.click();
     }

     // Get the title of Login Page
     public String getLoginTitle() {
           return titleText.getText();
     }

     public void login(String strUserName, String strPasword) {

           // Fill user name
           this.setUserName(strUserName);

           // Fill password
           this.setPassword(strPasword);

           // Click Login button
           this.clickLogin();
     }
}

HomePage. java

package PageObjectModel;

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

public class HomePage {
     WebDriver driver;

     @FindBy(id = "welcome")
     WebElement homePageUserName;

     public HomePage(WebDriver driver) {
           this.driver = driver;

           // This initElements method will create all WebElements
           PageFactory.initElements(driver, this);
     }

     // Get the User name from Home Page
     public String getHomePageText() {
           return homePageUserName.getText();
     }
}

Step 4 –  Create test class for the tests of these pages – POMTest

POMTest.java

package PageObjectModel;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class POMTest {

     WebDriver driver;
     Login objLogin;
     HomePage objHomePage;
 
     @BeforeTest
     public void setup() {
          System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
           driver = new FirefoxDriver();
           driver.manage().window().maximize();
           driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
           driver.get("https://opensource-demo.orangehrmlive.com/");
     } 

     /**
      *
      * This test go to https://opensource-demo.orangehrmlive.com/ Verify login page
      * title as LOGIN Panel Login to application Verify the home page using welcome
      * message
      *
      */

     @Test(priority = 0)
     public void loginTest() {

           // Create Login Page object
           objLogin = new Login(driver);

           // Verify login page text
           String loginPageTitle = objLogin.getLoginTitle();
           Assert.assertTrue(loginPageTitle.contains("LOGIN Panel"));
     }

     @Test(priority = 1)
     public void HomeTest() {

           // login to application
           objLogin.login("Admin", "admin123");

           // go the next page
           objHomePage = new HomePage(driver);

           // Verify home page
           Assert.assertTrue(objHomePage.getHomePageText().contains("Welcome"));
     }

     @AfterTest
     public void close() {
           driver.close();
     }
}

Step 5 – To run the test, right click and select as Run As and then select TestNG Test.

Step 6 – Create TestNG.xml

You can add TestNG.xml and run the tests from there also.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "PageObjectModel">
  <test name = "PageObjectModel Tests">
    <classes>
          <class name = "com.example.pageobjectmodel.tests.POMTest"/>
     </classes>  
   </test>
</suite>

Step 7 – Run the tests from TestNG.xml

Right click on TestNG.xml and select Run As TestNG Suite.

The execution status looks like as shown below.

Step 8 -TestNG Report Generation

Once the execution is finished, refresh the project. It will create a test-output folder containing various reports generated by TestNG. Below is the screenshot of the report folder.

Image of Index.html report

Image of emailable-report.html

Selenium Tutorials

 HOME

                 

Selenium is not a single automation Tool like QTP, but it is basically a suite of software’s or set of JAR files to automate web browser across various browsers. Selenium is used by many companies, but few to mention are Netflix, Google, HubSpot, Fitbit, and more.

  Selenium – Introduction, Installation, Test Script
Chapter 1 Introduction to Selenium Automation Tool
Chapter 2 How to Download & Install Java JDK 11 in Windows
Chapter 3 How to Download and Install Eclipse IDE
Chapter 4 How to install IntelliJ on Windows
Chapter 5 How to Download & Install Selenium WebDriver 
Chapter 6  How to create first Selenium WebDriver Script using Java

Selenium – Basic & Advance concepts of WebDriver

 Locators in Selenium

 Chapter 1 How to Locate Elements in Chrome, Firefox and IE Browsers for creating Selenium Scripts
Chapter 2 Locators in Selenium – Locate by ID, ClassName,  Name, TagName,  LinkText, PartialLinkText
Chapter 3 Dynamic XPath  in Selenium WebDriver
Chapter 4 CSS Selector in Selenium WebDriver

WebElements in Selenium

Chapter 1 Difference between FindElement and FindElements in WebDriver
Chapter 2 Difference between getText() and getAttribute() method in WebDriver
Chapter 3 WebDriver Browser Commands – get,  getTitle, getCurrentUrl, getPageSource, getClass, close, quit in WebDriver
Chapter 4 WebDriver Navigation Commands – Navigate, Forward, Back, Refresh in  WebDriver
Chapter 5 Selenium Form WebElement Commands – Sendkeys, Clear, Click,Submit
Chapter 6 How to automate selecting Checkbox and Radio Buttons in WebDriver
Chapter 7 How to Select value from Drop down list or perform Multiple Selection  Operations in WebDriver
Chapter 8 How to get all options in a DropDown list in WebDriver
Chapter 9 How to automate Radio Button in WebDriver
Chapter 10 How to automate BootStrap DropDown using WebDriver
Chapter 11 Implicit, Explicit and Fluent Wait in WebDriver
Chapter 12 What is Fluent Wait in Selenium WebDriver
Chapter 13 Switch Window Commands in Selenium WebDriver
Chapter 14 How to handle Alerts in Selenium WebDriver
Chapter 15 How to handle Dynamic Web Tables using Selenium WebDriver
Chapter 16 How to get all the values from a Dynamic Table in Selenium WebDriver 

Advance Selenium

Chapter 1 JavaScript and JavaScript Executor in Selenium
Chapter 2 Execute JavaScript with executeScript() Method in Selenium
Chapter 3 Execute JavaScript with executeAsyncScript() Method in Selenium
Chapter 4 Actions Class in Selenium WebDriver
Chapter 5 Drag and Drop action in Selenium WebDriver
Chapter 6 How to Capture Screenshot in Selenium Webdriver
Chapter 7 How to use FileHandler Class to take Screenshot in Selenium WebDriver
Chapter 8  How to Upload a File using Selenium Webdriver
Chapter 9 How to download and install Apache POI
Chapter 10 How to read data from Excel in Java
Chapter 11 How to write data in Excel in Java
Chapter 12 How to update existing excel in Java

Frameworks

Chapter 1 Page Object Model with Page Factory in Selenium
Chapter 2 Page Object Model with Selenium and Cucumber
Chapter 3 Integration of Cucumber with Selenium and JUnit
Chapter 4 Integration of Cucumber with Selenium and TestNG

How to Upload a File using Selenium Webdriver

HOME

We often face the problem where we have to upload a file in Web Application. This can be easily achieved in Selenium. We are using sendKeys() method to set the value of the file to upload. In this tutorial, will see how to upload a document in Selenium.

Let’s explain this with the help of an example.

1) Launch new Browser and open “https://demoqa.com/upload-download&#8221;
2) Locate the button “Choose File” by using xpath
3) Use sendkeys() to upload the file
4) After uploading the file, verify the message displayed on web page
5) Close the browser

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class UploadDemo {
    public static void main(String args[]) {
 
        System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\webdrivers\\window\\chromedriver.exe");
 
        // Initiate Chrome browser
        WebDriver driver = new ChromeDriver();
        driver.get("https://demoqa.com/upload-download");
 
        // Maximize the browser
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 
        // Locating upload button
        WebElement upload = driver.findElement(By.id("uploadFile"));
                        
        //Upload the file
        upload.sendKeys("C:\\Users\\Vibha\\Desktop\\SeleniumTest.txt");
 
        String Message = driver.findElement(By.id("uploadedFilePath")).getText();
        System.out.println("Message is :" + Message);
 
        // close the browser
        driver.close();
     }
}

The web page after uploading the file looks something like as shown below

How to use FileHandler Class to take Screenshot in Selenium WebDriver

 HOME

In the previous post, I have explained how to capture screenshots in Selenium using FileUtils. In this post, will see another way of capturing the screenshots in Selenium.

FileHandler is new Class in Selenium which help us to store screenshots, create directory and so on. You can get full documentation of FileHandler here

Step 1- Import the new package which is

import org.openqa.selenium.io.FileHandler;

Step 2 – To capture a screenshot in Selenium, we can make use of an interface, called TakesScreenshot. This method indicates the driver, that it can capture a screenshot and store it in different ways

TakesScreenshot ts = (TakesScreenshot) driver;

Step 3 – In order to capture screenshot and store it in a particular location, there is a method called “getScreenshotAs“, where OutputType defines the output type for a screenshot.

File source = ts.getScreenshotAs(OutputType.FILE);

Step 4- Call copy method of FileHandler Class which is static method and will ask two argument First is src and another is destination. Code will look like 

FileHandler.copy(source, new File("/Screenshots/SeleniumScreenshot" + System.currentTimeMillis() + ".png"));

Let’s see this in a Selenium program:-

import java.io.File;
 
import java.io.IOException; 
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.io.FileHandler;
 
public class ScreenshotExample {
      public static void main(String[] args) throws IOException {

            System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
            WebDriver driver = new FirefoxDriver();

            // Maximize the window
            driver.manage().window().maximize();
            driver.get("https://configureselenium.blogspot.com/");

            // Convert web driver object to TakeScreenshot
            TakesScreenshot ts = (TakesScreenshot) driver;

            // Call getScreenshotAs method to create image file
            File source = ts.getScreenshotAs(OutputType.FILE);

            // Copy file at destination
            FileHandler.copy(source, new File("./Screenshots/SeleniumScreenshot" + System.currentTimeMillis() + ".png"));
            System.out.println("the Screenshot is taken");

            // close the current browser
            driver.quit();
      } 
 
}

A folder with name “Screenshots” created and the screenshot placed in that folder as you can see the image below

The Screenshot looks like something as shown below

How to Capture Screenshot in Selenium Webdriver

 HOME

In Automation, it is advisable to take screenshots of failed test cases for further analysis and proof of failure. Selenium provides the capability to take screenshot. But, before we see how to capture Screenshot in Selenium, we need to add a dependency in the Maven project.

Recently Selenium has done some changes in recent version so if you are using Selenium 3.6.0 then you need to add below jar to project or if you are using then you can provide below dependency in project.

https://mvnrepository.com/artifact/commons-io/commons-io

To capture a screenshot in Selenium, we can make use of an interface, called TakesScreenshot. This method indicates the driver, that it can capture a screenshot and store it in different ways

TakesScreenshot ts = (TakesScreenshot) driver;

In order to capture screenshot and store it in a particular location, there is a method called “getScreenshotAs“, where OutputType defines the output type for a screenshot.

File source = ts.getScreenshotAs(OutputType.FILE);

Copy file to Desired Location

FileUtils.copyFile(source, newFile("./Screenshots/Selenium" + System.currentTimeMillis() + ".png"));

Let’s see the complete program

import java.io.File;
 
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class ScreenshotDemo {
      public static void main(String[] args) throws IOException {
                        
          System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\webdrivers\\window\\chromedriver.exe");
          WebDriver driver = new ChromeDriver();
                        
          // Maximize the window
          driver.manage().window().maximize();
          driver.get("https://configureselenium.blogspot.com/");
                        
          // Convert web driver object to TakeScreenshot
          TakesScreenshot ts = (TakesScreenshot) driver;
                        
          // Call getScreenshotAs method to create image file
           File source = ts.getScreenshotAs(OutputType.FILE);
                        
          // Copy file at destination
          FileUtils.copyFile(source, new File("./Screenshots/Selenium" + System.currentTimeMillis() + ".png"));
           System.out.println("the Screenshot is taken");
                        
          // close the current browser
          driver.quit();
     }
 
}

A folder with name Screenshots created and the screenshot is placed in that folder as you can see the image below

The Screenshot looks like something below

If you don’t want to use Maven Dependency common-io, then you can use FileHandler from

import org.openqa.selenium.io.FileHandler;
 
FileHandler.copy(source, new File("C:\\Screenshots\\Selenium" + System.currentTimeMillis() + ".png"));