How to run Edge tests in headless mode in Selenium4

HOME

This tutorial explains the steps to run the Selenium tests for Chrome browser and Firefox in headless mode. We are going to run the tests in Selenium 4.

There are 2 ways to add dependencies to the Selenium project.

Manually add the dependencies to the project

Download Selenium Version from here

Download Microsoft Edge Binary from here

Download the latest version of WebDriverManager

Once the Selenium and WebDriverManager folders are downloaded, unzip the folder. Once the zip file is extracted, reference these jar files in the project. For this, navigate to project properties and click Build Path-> Configure Build Path in Eclipse. Click “Add External Jars“. After clicking on the “Add External JARs“, selected all the extracted JARs. The JARs files are present in the project.

Add the below dependencies to pom.xml or build.gradle

Selenium 4

 <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.1.2</version>
</dependency>

What is headless browser?

A headless browser is like any other browser, but without a Head/GUI (Graphical User Interface).  A headless browser is used to automate the browser without launching the browser. While the tests are running, we could not see the browser, but we can see the test results coming on the console.

We know that to execute Selenium automation scripts on browsers like edge, we must download the binary files of EDGE driver – msedgedriver. After this, we need to set the path to these binaries in the automation script or add the classpath location. Here, we want to execute Selenium WebDriver automation scripts on the Microsoft Edge browser, then you need first to download msedgedriver.exe and then use the System.setProperty  method to set its path as follows:

		// Set the path of EdgeDriver
		System.setProperty("webdriver.edge.driver",
				"C:\\Users\\Vibha\\Software\\edgedriver_win64\\msedgedriver.exe");

The complete program looks like as shown below:

import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

public class EdgeHeadlessInSelenium4 {

	public static void main(String[] args) {
		// Set the path of EdgeDriver
		System.setProperty("webdriver.edge.driver",
				"C:\\Users\\Vibha\\Software\\edgedriver_win64\\msedgedriver.exe");

		// Create an object of Edge Options class
		EdgeOptions edgeOptions = new EdgeOptions();

		// pass the argument –headless to Edge Options class.
		edgeOptions.addArguments("--headless");

		// Create an object of WebDriver class and pass the Edge Options object as
		// an argument
		WebDriver driver = new EdgeDriver(edgeOptions);

		System.out.println("Executing Edge Driver in Headless mode..");
		driver.get("https://duckduckgo.com/");

		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL  : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}

}

How to run headless Microsoft Edge Tests in Selenium using WebDriverManager?

WebDriverManager

<!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.1.0</version>
</dependency>

WebDriverManager has an automated way to download browser executables(exes) or binaries. It supports different browsers like Chrome, Firefox, Microsoft Edge, Internet Explorer, Opera, or PhantomJS.

WebDriverManager.edgedriver().setup: checks for the latest version of the specified WebDriver binary. If the binaries are not present on the machine, then it will download the WebDriver binaries. Next, it instantiates the Selenium WebDriver instance with the EdgeDriver.

import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class EdgeHeadlessWithWebDriverManagerInSelenium4 {

	public static void main(String[] args) {

		// WebDriverManager downloads Edge browser executables or binaries.
		WebDriverManager.edgedriver().setup();

		// Create an object of Edge Options class
		EdgeOptions edgeOptions = new EdgeOptions();

		// pass the argument –headless to Edge Options class.
		edgeOptions.addArguments("--headless");

		// Create an object of WebDriver class and pass the Edge Options object as
		// an argument
		WebDriver driver = new EdgeDriver(edgeOptions);

		System.out.println("Executing Edge Driver in Headless mode..");

		driver.get("https://www.bing.com/");
		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}
}

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

How to disable infobar warning for Chrome tests in Selenium

HOME

This tutorial explains the steps to disable infobar warning generated by Selenium for running tests in Chrome. Selenium tests run on Chrome shows a warning message – “Chrome is being controlled by automated test software as shown in the below image.”

We want to run the Selenium tests on Chrome, but without above shown warning message. This can be achieved by using excludeSwitches.

chromeOptions.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation"));

The complete program is shown below:

import java.util.Arrays;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class ChromeDisableInfobars {

	public static void main(String[] args) {

		WebDriverManager.chromedriver().setup();

		// Create an object of Chrome Options class
		ChromeOptions chromeOptions = new ChromeOptions();

		// prevents Chrome from displaying the notification 'Chrome is being controlled
		// by automated software'
		chromeOptions.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation"));

		// Create an object of WebDriver class and pass the Chrome Options object as an
		// argument
		WebDriver driver = new ChromeDriver(chromeOptions);

		driver.get("https://duckduckgo.com/");

		System.out.println("Title of Page :" + driver.getTitle());

		// close the browser
		driver.quit();

	}
}

We are done. Congratulations!! Happy Learning.

How to run Firefox tests in headless mode in Selenium

HOME

This tutorial explains the steps to run the Selenium tests on Firefox browser in headless mode. We are going to run the tests in Selenium. To run the Selenium tests on Chrome browser in headless mode, refer this tutorial.

To start with, we need to add dependencies to the project.

Manually add the dependencies to the project

Download Selenium Version from here

Download Firefox Binary from here – Version 97.0.1

Download the latest version of WebDriverManager (Download this if you want to use WebDriverManager to download browser executables(exes) or binaries automatically, then skip downloading FireFox Binary).

Add the below dependencies to pom.xml or build.gradle.

Selenium 3

<!-- 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>

What is headless browser?

A headless browser is like any other browser, but without a GUI (Graphical User Interface).  A headless browser is used to automate the browser without launching the browser. While the tests are running, we could not see the browser, but we can see the test results coming on the console. This makes the test execution faster than normal execution. This is suitable for parallel testing as UI tests needs a lot of memory and resources.

The path of Gecko Driver (used for Firefox browser) needs to be set up in the Test using System.setProperty().Here, we use the methods setHeadless (true) of the FirfoxOptions class provided by Selenium WebDriver.

The complete program looks like as shown below:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

public class FirefoxOptionsHeadless1 {

	public static void main(String[] args) {

		// Set the path of GeckoDriver
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver\\geckodriver.exe");

		// Create an object of Firefox Options class
		FirefoxOptions options = new FirefoxOptions();

		// Set Firefox Headless mode as TRUE
		options.setHeadless(true);

		// Create an object of WebDriver class and pass the Firefox Options object
		// as an argument
		WebDriver driver = new FirefoxDriver(options);

		// Navigate to site url
		driver.get("https://duckduckgo.com/");

		System.out.println("Executing Firefox Driver in Headless mode..");
		System.out.println("Page Title : " + driver.getTitle());
		System.out.println("Page URL  : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();
	}
}

How to run headless Firefox Tests in Selenium using WebDriverManager?

WebDriverManager

<!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.1.0</version>
</dependency>

WebDriverManager.firefoxdriver().setup(): checks for the latest version of the specified WebDriver binary. If the binaries are not present on the machine, then it will download the WebDriver binaries. In this case, it is not needed to download Firefox binary and set up the path

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class FirefoxOptionsHeadless2 {

	public static void main(String[] args) {

		WebDriverManager.firefoxdriver().setup();

		// Create an object of Firefox Options class
		FirefoxOptions options = new FirefoxOptions();

		// Set Firefox Headless mode as TRUE
		options.setHeadless(true);

		// Create an object of Firefox Driver class and pass the Firefox Options object
		// as an argument
		WebDriver driver = new FirefoxDriver(options);

		// Navigate to the url
		driver.get("https://duckduckgo.com/");

		System.out.println("Executing Firefox Driver in Headless mode..");
		System.out.println("Page Title : " + driver.getTitle());
		System.out.println("Page URL  : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();
	}

}

Congratulations!! We have run the tests in headless mode in FireFox.

How to run Selenium Tests using on Internet Explorer

HOME

Internet Explorer is going away in near future. But still it is a browser which holds around 1% of browser market share. When anyone refers to automated browser testing, it somehow means that the testing will be performed on the latest browsers like Chrome, Firefox, etc. But along with these browsers, it is also expected to work on Internet Explorer (IE).

The Internet Explorer driver that is used by Selenium Tests can be downloaded from here.

In order to run the Selenium Tests on IE, it is needed to set the %PATH%.

How to add %PATH%

Go To -> View Advanced System Settings -> Environment Variables ->Clicks on the Path and add the path where IE binary is located on the machine.

How to run tests using Selenium IE driver in Selenium Java?

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class IEDemo {

	public WebDriver driver;

	@Before
	public void setUp() {

		System.setProperty("webdriver.ie.driver",
				"C:\\Users\\Vibha\\Software\\IEDriverServer_x64_2.39.0\\IEDriverServer.exe");

		driver = new InternetExplorerDriver();
	}

	@Test
	public void verifyPageTitle() {

		System.out.println("Opening Internet Explorer Web Browser");
		driver.get("https://www.bing.com/");
		System.out.println("Title of Page : " + driver.getTitle());
		Assert.assertEquals(driver.getTitle(), "Bing");
	}

	@Test
	public void verifyPageUrl() {

		System.out.println("Opening Internet Explorer Web Browser");
		driver.get("https://www.bing.com/");
		System.out.println("URL of Page : " + driver.getCurrentUrl());
		Assert.assertEquals(driver.getCurrentUrl(), "https://www.bing.com/");
	}

	@After
	public void tearDown() {

		// Close the driver
		driver.close();

	}
}

Execution

The string webdriver.ie.driver is set to the location which contains the Selenium IE driver. The InternetExplorerDriver method is used for instantiating the IE driver class.

The test method is implemented under the @Test annotation.

 In the tearDown method, the resources held by IE driver are freed using the close() method in Selenium.

Congratulations!! We are able to open an Internet Explorer browser and perform tests. Happy Learning!!

How to manage driver executables using WebDriverManager

HOME

The traditional way to use any browser in Selenium tests is to download browser binaries and we need to set the path of these files in our script like below or its location should be added to the classpath.

System.setProperty("webdriver.chrome.driver", "/absolute/path/to/binary/chromedriver");

The process of manually downloading and managing these drivers for each operating systems is very painful. We also have to check when new versions of the binaries are released / new browsers versions are released. We should check the compatibility for all the executables and add it.

How to download all the driver executables automatically ???

The automatic download of the drivers can be done by WebDriverManager. WebDriverManager is a library that allows controlling web browsers programmatically. It provides a cross-browser API that can be used to drive web browsers (e.g., Chrome, Edge, or Firefox, among others) using different programming languages (e.g., Java, JavaScript, Python, C#, or Ruby). The primary use of Selenium WebDriver is implementing automated tests for web applications.

The communication between the WebDriver API and the driver binary is done using a standard protocol called W3C WebDriver (formerly the so-called JSON Wire Protocol). Then, the communication between the driver and the browser is done using the native capabilities of each browser.

How To add WebDriverManager to a Selenium project manually?

Download the latest version of WebDriverManager from here.

It will download a zip file. Now extract the jar/zip file. It will show various jar under the folder, as shown below:

Once we extract the zip file, we have to reference these jar files in our project. For this, navigate to project properties and click Build Path-> Configure Build Path in Eclipse

Click “Add External Jars” as per the steps highlighted below to include all the WebDriverManager jars extracted.

After clicking on the “Add External JARs“, all the selected extracted JARs are added to the project.

When this finishes, the project references show these referenced jars in the project explorer as highlighted below, and they are ready to be consumed in the Selenium test scripts.

Chrome

The below code snippet shows a quick usage of WebDriverManager with Chrome:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class Demo {

	public static void main(String[] args) {

		WebDriverManager.chromedriver().setup();

		// Create an object of Chrome Options class
		ChromeOptions chromeOptions = new ChromeOptions();

		// Create an object of WebDriver class and pass the Chrome Options object as
		// an argument
		WebDriver driver = new ChromeDriver(chromeOptions);

		System.out.println("Executing Chrome Driver");

		driver.get("https://www.bing.com/");
		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}
}

FireFox Driver

The below code snippet shows a quick usage of WebDriverManager with FireFox:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class FireFoxDemo {

	public static void main(String[] args) {

		WebDriverManager.firefoxdriver().setup();

		// Create an object of Firefox Options class
		FirefoxOptions firefoxOptions = new FirefoxOptions();

	    // Create an object of WebDriver class and pass the Firefox Options object
		// as an argument
		WebDriver driver = new FirefoxDriver(firefoxOptions);

		System.out.println("Executing Firefox Driver");

		driver.get("https://www.bing.com/");
		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}
}

Microsoft Edge

The below code snippet shows a quick usage of WebDriverManager with Microsoft Edge:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class EdgeDemo {

	public static void main(String[] args) {

		WebDriverManager.edgedriver().setup();

		// Create an object of Edge Options class
		EdgeOptions edgeOptions = new EdgeOptions();

		// Create an object of WebDriver class and pass the Edge Options object
		// as an argument
		WebDriver driver = new EdgeDriver(edgeOptions);

		System.out.println("Executing Microsoft Edge Driver");

		driver.get("https://www.bing.com/");
		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}
}

The basic use of these managers is the following:

WebDriverManager.chromedriver().setup();
WebDriverManager.firefoxdriver().setup();
WebDriverManager.edgedriver().setup();
WebDriverManager.operadriver().setup();
WebDriverManager.chromiumdriver().setup()
WebDriverManager.iedriver().setup();

How To add WebDriverManager to a Selenium project using Maven or Gradle?

To use WebDriverManager in a Maven built project, the below mentioned dependency is needed to add to the pom.xml.

<!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.1.0</version>
</dependency>

For Gradle project, add the below to the build.gradle.

dependencies {
    testCompile("io.github.bonigarcia:webdrivermanager:5.1.0")
}

How to instantiate a specific browser version using WebDriverManager?

WebDriverManager provides an ability to download specific version of browser. For example, the latest chromedriver version is 100.0.4896.20 (released on 2022-03-04). But if we want an earlier version, say, Chromedriver version 98.0.4758.102, we have to add the following code.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class Demo {

	public static void main(String[] args) {

		WebDriverManager.chromedriver().driverVersion("98.0.4758.102").setup();

		// Create an object of Chrome Options class
		ChromeOptions chromeOptions = new ChromeOptions();

		// Create an object of WebDriver class and pass the Chrome Options object as
		// an argument
		WebDriver driver = new ChromeDriver(chromeOptions);

		System.out.println("Executing Chrome Driver");

		driver.get("https://www.bing.com/");
		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}
}

As we can see from the above screenshot, as a result of executing the above program, the Chromedriver started successfully. We can see the details of starting the chrome driver instance in the first line of output. Here we have set the Chrome version to 98.0.4758.102″.

Congratulations!! We have learnt to download drivers automatically.

How to run Chrome tests in headless mode in Selenium

HOME

This tutorial explains the steps to run the Selenium tests for Chrome browser in headless mode. We are going to run the tests in Selenium 3.

There are 2 ways to add dependencies to the Selenium project.

  1. Manually add the dependencies to the project.

Download Selenium Version from here

Download ChromeDriver Binary

Download the latest version of WebDriverManager

Once the Selenium and WebDriverManager folders are downloaded, unzip the folder. Once the zip file is extracted, reference these jar files in the project. For this, navigate to project properties and click Build Path-> Configure Build Path in Eclipse. Click “Add External Jars“. After clicking on the “Add External JARs“, selected all the extracted JARs. The JARs files are present in the project.

2. Add the below dependencies to pom.xml or build.gradle.

Add below dependencies to the project.

Selenium 3

<!-- 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>

What is headless browser?

A headless browser is like any other browser, but without a Head/GUI (Graphical User Interface).  A headless browser is used to automate the browser without launching the browser. While the tests are running, we could not see the browser, but we can see the test results coming on the console.

Headless browser testing is generally faster when compared to actual UI testing as it doesn’t wait for the whole page to render before performing any action.

When we need to execute automated test cases remotely on a server or in any of the build and release pipelines for continuous integration servers like Gitlab or Jenkins, it is not always possible to install real browsers on such remote machines. We can use headless browsers to run automation tests efficiently.

It is easy to perform multi-tasking with a Headless browser. The browser or our machine can do anything else while the tests run in the background.

We know that to execute Selenium automation scripts on browsers like chrome or firefox, we must download the binary files of these drivers like chromedriver and geckodriver, etc. After this, we need to set the path to these binaries in the automation script or add the classpath location. Here, we want to execute Selenium WebDriver automation scripts on the Chrome browser, then you need first to download chromedriver.exe and then use the System.setProperty  method to set its path as follows:

	// Set the path of ChromeDriver
	System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\Vibha\\Software\\chromedriver_win32_98.0.4758.102\\chromedriver.exe");

The complete program looks like as shown below:

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class ChromeOptionsHeadless1 {

	public static void main(String[] args) {

		// Set the path of ChromeDriver
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\SingVi04\\Vibha\\Software\\chromedriver_win32_98.0.4758.102\\chromedriver.exe");

		// Create an object of Chrome Options class
		ChromeOptions options = new ChromeOptions();

		// pass the argument –headless to Chrome Options class.
		options.addArguments("--headless");

		// Create an object of Chrome Driver class and pass the Chrome Options object as
		// an argument
		ChromeDriver driver = new ChromeDriver(options);

		System.out.println("Executing Chrome Driver in Headless mode..");
		driver.get("https://duckduckgo.com/");

		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL  : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}
}

How to run headless Chrome Tests in Selenium using WebDriverManager?

WebDriverManager

<!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.1.0</version>
</dependency>

WebDriverManager has an automated way to download browser executables(exes) or binaries. It supports different browsers like Chrome, Firefox, Microsoft Edge, Internet Explorer, Opera, or PhantomJS.

WebDriverManager.chromedriver().setup: checks for the latest version of the specified WebDriver binary. If the binaries are not present on the machine, then it will download the WebDriver binaries. Next, it instantiates the Selenium WebDriver instance with the ChromeDriver.

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class ChromeOptionsHeadless2 {

	public static void main(String[] args) {

		// WebDriverManager downloads chrome browser executables or binaries.
		WebDriverManager.chromedriver().setup();

		// Create an object of Chrome Options class
		ChromeOptions options = new ChromeOptions();

		// pass the argument –headless to Chrome Options class.
		options.addArguments("--headless");

		// Create an object of Chrome Driver class and pass the Chrome Options object as
		// an argument
		ChromeDriver driver = new ChromeDriver(options);

		System.out.println("Executing Chrome Driver in Headless mode..");
		driver.get("https://duckduckgo.com/");

		System.out.println("Title of Page :" + driver.getTitle());
		System.out.println("Page URL  : " + driver.getCurrentUrl());

		// Close the driver
		driver.close();

	}

}

Congratulations!! We are able to run Chrome tests in Selenium in headless mode.

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!!