Debarghya

Myself Debarghya Roy, I am an Engineering ARCHITECT working with fortune 5 company and an open source contributor, having around 12 years of experience/expertise in various Technology stack. I have worked with various technologies such as Java,C#,Python,Groovy, UI Automation(Selenium), Mobile Automation(Appium), API/Backend Automation,Performance Engineering(JMeter, Locust), Security Automation(MobSF,OwAsp,Kali Linux, Astra,ZAP etc), RPA,Process Engineering Automation,Mainframe Automation,Back End Development with SpringBoot,Kafka,Redis,RabitMQ,ELK stack, GrayLog, Jenkins and also having experience in Cloud Technologies, DevOps etc. I live in Bangalore ,India with my wife and have passion towards Blogging , music , playing guitar and my Philosophy of life is Education for All which gave the birth of LambdaGeeks. Lets connect over linked-in - https://www.linkedin.com/in/debarghya-roy/

Complete Page Object Model Framework -2021

In this tutorial, we will learn about the Page Object Model, and also we will design and develop the Page Object Model framework from scratch. 

We had discussed all the types of framework in Selenium, including Page Object Model , here we would go through in-depth.

Page Object Model Framework
Page Object Model Framework Development

We will design and develop the below features .

What is Page Object Model Framework design in Selenium  

Page Object Model is a Design Model for building Selenium test Automation, where we distribute our whole Application under test into small pages (sometimes a webpage is considered as a page, and sometimes a subpart of a Webpage is also considered as a Page ). Each of these pages is represented as a Java class, and the functionalities of the pages are written as different methods in the respective page’s Java class.

Let’s say you have a Gmail application which you will automate; hence the Gmail login page is there where you have few major functionalities such as login, create an account, etc.

Here we will create a java class as GmailLoginPage, and we will write methods named as performLogin() , createUserAccount, etc. 

Let’s say once you are logged in to your Gmail account, you have many features like inbox, sent items, trash, etc. Now here, for each module, you create a Java class and keep their functionalities as Java methods inside respective java classes. 

Why Page Object Model

Page Object Model is a very robust and advanced framework design model where you can take care of the below areas : 

Hybrid Page Object Model Framework Structure

In the previous tutorial, we understood the hybrid Page Object Model, and now we will design and develop a framework.

The architecture of the Page Object Model framework

We can simply create a maven project and incorporate the dependencies in POM.xml file thats required for the framework initially which looks like this one : 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>demo</groupId>
	<artifactId>DemoAutomation</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>DemoAutomation</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>7</source>
					<target>7</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.4.2</version>
				<configuration>
					<suiteXmlFiles>
						<suiteXmlFile>testNg.xml</suiteXmlFile>
					</suiteXmlFiles>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<reporting>
		<plugins>
			<plugin>
				<groupId>org.reportyng</groupId>
				<artifactId>reporty-ng</artifactId>
				<version>1.2</version>
				<configuration>
				    <outputdir>/target/testng-xslt-report</outputdir>
				    <sorttestcaselinks>true</sorttestcaselinks>
			            <testdetailsfilter>FAIL,SKIP,PASS,CONF,BY_CLASS</testdetailsfilter>
				    <showruntimetotals>true</showruntimetotals>
				</configuration>
			</plugin>
		</plugins>
	</reporting>
	<dependencies>
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-server</artifactId>
			<version>2.53.0</version>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>6.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.8</version>
		</dependency>

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

		<dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6</version>
		</dependency>
	</dependencies>
</project>

After that, we will build small modules and utilities, where we have attached this snapshot below just to provide high-level insights/view. We will build utilities one by one. 

Here are the below modules that we will develop; we have provided the code snippet for the same : 

DriverUtils – Page Object Model Framework

This module provides all the utilities and support to work with the various browsers (Chrome, Firefox, etc.).This utility is based on the Factory design pattern, as we discussed in the previous tutorial here.

package com.base.driverUtils;

import org.openqa.selenium.WebDriver;

public interface IDriver {

  public WebDriver init(String browserName);
}

Localdriver implementation, which will execute locally with Selenium Webdriver :

package com.base.driverUtils;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class LocalDriver implements IDriver {

  public WebDriver init(String browserName) {
     switch (browserName) {
     case "firefox":
        return new FirefoxDriver();

     case "chrome":
        System.setProperty("webdriver.chrome.driver",
              "..\\DummyAutomation\\DriverExe\\chromedriver.exe");
        return new ChromeDriver();

     case "ie":
        System.setProperty("webdriver.ie.driver",
              "..\\DummyAutomation\\DriverExe\\IEDriverServer.exe");
        return new InternetExplorerDriver();
     default:
        return new FirefoxDriver();
     }
  }

}

Remote Webdriver: To work with a remote webdriver (such as Selenium Grid), you need a remote reference of the browser driver, which goes like : 

package com.base.driverUtils;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class RemoteDriver implements IDriver {

  DesiredCapabilities caps;
  String remoteHuburl;

  @Override
  public WebDriver init(String browserName) {
     switch (browserName) {
     case "firefox":
        try {
           return new RemoteWebDriver(new URL(remoteHuburl), caps.firefox());
        } catch (MalformedURLException e2) {
           // TODO Auto-generated catch block
           e2.printStackTrace();
        }
     case "chrome":
        try {
           return new RemoteWebDriver(new URL(remoteHuburl), caps.chrome());
        } catch (MalformedURLException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        }
     case "ie":
        try {
           return new RemoteWebDriver(new URL(remoteHuburl), caps.internetExplorer());
        } catch (MalformedURLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }
     default:
        try {
           return new RemoteWebDriver(new URL(remoteHuburl), caps.firefox());
        } catch (MalformedURLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }
     }
     return null;
  }
 

}

Factory Driver class: This provides us the driver class (remote/local) object to initiate the browsers of your choice. We will take the type of driver(local or remote) and browser (chrome or firefox etc.) through the configuration file(we have used a properties file to keep the configurations, which we will share shortly )

package com.base.driverUtils;

public class DriverProvider {

  public IDriver getDriver(String typeOfDriverExecution){
     switch(typeOfDriverExecution){
     case "local":
        return new LocalDriver();
     case "remote":
        return new RemoteDriver();
     default :
        return new LocalDriver();
     }
  }
}

Now wherever you require the driver reference, you can simply create the object of the factory class object (DriverProvider in this case) and can initiate the driver browser instance.

Here is the very basic config file; you can create a properties file and store the values like this : 

modeOfExecution=local
browser=chrome
url=http://www.applicationUrl.com/

DataUtils-Page Object Model Framework: 

We have designed the data utilities here as the same Factory design pattern as we did from implementing the driver browser modules.

Here is the below code snippet for the same; in the framework, we have shown Excel utils and properties utils, you can enhance more to support other data utilities like YAML, PDF, etc.: 

The interface here goes like this: 

package com.base.dataUtils;

public interface IDataProvider {

  public Object[][] fetchDataSet(String... dataFileInfo);
  public String fetchData(String... dataFileInfo);
}

Here is the implementation for Excel Data provider

package com.base.dataUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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

public class ExcelDataProvider implements IDataProvider {

  FileInputStream fis = null;
  private static XSSFWorkbook workBook = null;
  private static XSSFCell Cell;
  private static XSSFSheet sheet;

  public static String[][] excelDataSet = null;

  @Override
  public Object[][] fetchDataSet(String... dataFileInfo) {
     String excelFilePath = dataFileInfo[0];
     String excelSheetName = dataFileInfo[1];
     File file = new File(excelFilePath);

     try {
        fis = new FileInputStream(file);
     } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
     }
     try {
        workBook = new XSSFWorkbook(fis);
     } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
     }
     sheet = workBook.getSheet(excelSheetName);
     int ci, cj;
     int rowCount = sheet.getLastRowNum();
     int totalCols = sheet.getRow(0).getPhysicalNumberOfCells();
     excelDataSet = new String[rowCount][totalCols - 1];
     ci = 0;
     for (int i = 1; i <= rowCount; i++, ci++) {
        cj = 0;
        for (int j = 1; j <= totalCols - 1; j++, cj++) {

           try {
              excelDataSet[ci][cj] = getCellData(i, j);
           } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           }
        }
     }
     return excelDataSet;

  }

  public static String getCellData(int RowNum, int ColNum) throws Exception {

     try {

        Cell = sheet.getRow(RowNum).getCell(ColNum);

        int dataType = Cell.getCellType();

        if (dataType == 3) {

           return "";

        }

        else if (dataType == XSSFCell.CELL_TYPE_NUMERIC) {
           int i = (int) Cell.getNumericCellValue();
           return Integer.toString(i);
        }

        else {

           String CellData = Cell.getStringCellValue();

           return CellData;

        }
     } catch (Exception e) {

        throw (e);

     }

  }

  @Override
  public String fetchData(String... dataFileInfo) {
     // TODO Auto-generated method stub
     return null;
  }

}

Properties Data provider : 

package com.base.dataUtils;

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

public class PropertiesDataProvider implements IDataProvider {

  FileInputStream fis=null;

  @Override
  public Object[][] fetchDataSet(String... dataFileInfo) {
     // TODO Auto-generated method stub
     return null;
  }

  @Override
  public String fetchData(String... dataFileInfo) {

     String dataValue;
     String pathToFile = dataFileInfo[0];
     String key = dataFileInfo[1];
     Properties properties = new Properties();
     try {
        fis=new FileInputStream(pathToFile);
        properties.load(fis);
     } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
     }
     dataValue = properties.getProperty(key);
     return dataValue;
  }

}

The factory class for this data Utilities

package com.base.dataUtils;

public class DataHelperProvider {

  public IDataProvider getDataHelperProvider(String typeOfDataHandler) {
     switch (typeOfDataHandler) {
     case "excel":
        return new ExcelDataProvider();
     case "properties":
        return new PropertiesDataProvider();
     }
     return null;

  }
}

WebAction utilities -Page Object Model Framework

In the utilities, we write all the utilities related to your Web actions like (click, sendkeys, screenshots, etc.), and we can utilize it in Page Methods to perform web actions to achieve the page functionalities as discussed earlier in this tutorial. 

Here is the code snippet for the WebAction Utilities : 

package com.base.webActionHelperUtils;

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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


public class WebActionsHelperUtils {

  protected WebDriver driver;

  public WebActionsHelperUtils(WebDriver driver) {

     this.driver = driver;
  }

  public void safeClick(By element) {

     waitForElementToBeClickAble(element, 30);
     driver.findElement(element).click();
  }

  public List<WebElement> getElements(By elements) {
     return driver.findElements(elements);
  }

  public void waitForWebElementsToBeDisplayed(By elements, int timeOuts) {
     WebDriverWait wait = new WebDriverWait(driver, timeOuts);
     wait.until(ExpectedConditions.visibilityOfAllElements(getElements(elements)));
  }

  public void waitForElementToBeClickAble(By element, int timeOutSeconds) {
     WebDriverWait waitForElement = new WebDriverWait(driver, timeOutSeconds);
     waitForElement.until(ExpectedConditions.elementToBeClickable(element));
  }

  public void waitForElementToBeDisplayed(By element, int timeOuts) {
     WebDriverWait wait = new WebDriverWait(driver, timeOuts);
     wait.until(ExpectedConditions.visibilityOfElementLocated(element));
  }

  public void enterTextIntoElement(By element, String textToBeEntered) {
     driver.findElement(element).sendKeys(textToBeEntered);
  }

  public String getText(By element) {
     return driver.findElement(element).getText();

  }

  public String getAttribute(By element, String attribute) {
     return driver.findElement(element).getAttribute(attribute);
  }

  public boolean isSelected(By element) {
     boolean isElementSelected = false;
     if (driver.findElement(element).isSelected() == true) {
        isElementSelected = true;
     }
     return isElementSelected;
  }

  public void clearField(By element) {
     driver.findElement(element).clear();
  }

  public void implicitlyWait(int timeOuts) {
     driver.manage().timeouts().implicitlyWait(timeOuts, TimeUnit.SECONDS);
  }

  public boolean isElementPresent(By element) {
     try {
        driver.findElement(element);
        return true;
     } catch (Exception e) {
        return false;
     }
  }

  public void switchToTab(int indexOfTab) {
     ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
     driver.switchTo().window(tabs.get(indexOfTab));

  }
}

Page Module utilities-Page Object Model Framework

Like we know, we have to create the Page class and keep the page functionalities in the page methods, so now let’s create the Page Module for the Page Object Model framework : 

Every Page Class again extends the WebAction Utils that we developed just now and implements the Page interfaces, where the page interfaces are nothing but the interfaces to keep the respective page’s Web Elements/locators.

Now Why we need interfaces to store the locators : 

Hence we used separate interfaces for separate page locators to store as by this approach; we solve all the above problem statements, which are time complexity, space complexity, and the clean and maintainable codebase as in interfaces, we don’t have to create objects to access locators.

package com.base.pageModules;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.base.commonUtils.JSonHandler;
import com.base.webActionHelperUtils.WebActionsHelperUtils;
import com.page.locatorModules.HomePageLocators;

public class HomePage extends WebActionsHelperUtils implements HomePageLocators {

  JSonHandler jsonHandler = new JSonHandler();

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

  public void enterSearchdataToSearchField(String searchData) {

     waitForElementToBeClickAble(SEARCH_BOX, 10);
     enterTextIntoElement(SEARCH_BOX, searchData);

  }

  public void navigatToUrl() {
     driver.get(url);
  }

  public void captureSearchSuggestion(String pathToJsonDataStore, String searchData) {
     List<WebElement> elements = getElements(SUGGESTION_BOX);
     jsonHandler.captureAndWriteJsonData(elements, pathToJsonDataStore, searchData);
  }

  public void genericWait(int timeOuts) {
     implicitlyWait(timeOuts);
  }

  public void clikcOnSelectedElement(String option) {
     int optionSelection = Integer.parseInt(option);
     safeClick(By.xpath("//div[@id='s-separator']/following-sibling::div[" + optionSelection + "]"));
  }

}

Likewise, you can keep on including the page features in the page different Page methods inside the respective page classes. 

Here is how the Page locators interfaces look like : 

package com.page.locatorModules;

import org.openqa.selenium.By;

public interface HomePageLocators {

 
  By SEARCH_BOX=By.id("twotabsearchtextbox");
  By SUGGESTION_BOX=By.xpath("//div[@id='suggestions']/div");
 
}

Now the next segment, you can create a baseSetUp or Basetest where you want to perform the initialization/data loading parts. Also, you could use @beforeTest, @beoforeClass methods in this class itself and use them in your test classes.

BaseSetup Class looks like : 

package com.demo.testS;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.DataProvider;

import com.base.dataUtils.DataHelperProvider;
import com.base.dataUtils.IDataProvider;
import com.base.driverUtils.DriverProvider;

public class BaseSetUp {

	public WebDriver driver;
	DriverProvider browserProvider = new DriverProvider();
	DataHelperProvider datahelperProvider = new DataHelperProvider();
	IDataProvider dataProvider = datahelperProvider.getDataHelperProvider("properties");
	IDataProvider dataProviderExcel = datahelperProvider.getDataHelperProvider("excel");
	public final String configProperties = "..\\DummyAutomation\\TestConfigsData\\config.properties";
	public String url = dataProvider.fetchData(configProperties, "url");
	String modeOfExecution = dataProvider.fetchData(configProperties, "modeOfExecution");
	String browserName = dataProvider.fetchData(configProperties, "browser");
	String pathToJasonDataStore = "..\\DummyAutomation\\ProductJsonData\\";
	String pathToExcelData = "..\\DummyAutomation\\TestConfigsData\\TestData.xlsx";

	public WebDriver getDriver() {
		return driver;
	}

	protected void setDriver() {
		driver = browserProvider.getDriver(modeOfExecution).init(browserName);
	}

	@DataProvider(name = "SearchFunctionality")
	public Object[][] getCityDetails() {
		Object[][] arrayObject = dataProviderExcel.fetchDataSet(pathToExcelData, "DataFeed");
		return arrayObject;
	}
}

Test Classes: As we would be using TestNG here, so you need to write @test method for the test script to be developed, such as : 

Here is the code snippet for the Test Classes  

package com.demo.testS;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.base.pageModules.HomePage;
import com.base.pageModules.SearchPage;

public class DemoTest extends BaseSetUp {

  HomePage homePage;
  SearchPage searchPage;

  @BeforeMethod
  public void setUpTest() {
     setDriver();
     homePage = new HomePage(driver);
     searchPage = new SearchPage(driver);
     homePage.navigatToUrl();
  }

  @Test(dataProvider = "SearchFunctionality")
  public void search(String searchData, String selectOption) {
     homePage.enterSearchdataToSearchField(searchData);
     homePage.genericWait(5);
     homePage.captureSearchSuggestion(pathToJasonDataStore, searchData);
     homePage.clikcOnSelectedElement(selectOption);
     searchPage.clickOnFirstProduct();
     searchPage.switchToProductSpecificPage();
     searchPage.captureProductData(pathToJasonDataStore, searchData);

  }

  @AfterMethod
  public void tearDown() {
     if (driver != null) {
        driver.quit();
     }
  }

}

TestNgXML file -Page Object Model framework

You would need to define an XML class for the testng.xml, which basically a unit test framework and controls the flow of your automation; you can mention the test classes there themselves.

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter" parallel="tests" thread-count="3">

<test name="DemoAutomation_TarGet">
<classes>
<class name="com.demo.testS.DemoTest"></class>

</classes>
</test>
</suite>

So with these activities, your basic Page Object Model framework should be ready now. If you want to Achieve the advanced version of your framework, then you could incorporate these below areas : 

Reporting Feature-Page Object Model Framework

You can use any reporting feature available like allure, extentreport, TestNG report, or advance reporting by using ELK stack, etc. 

Just to keep the simplicity, we are showing here the reporting feature with Extent report, which is having many features along with it and can be considered as an intermediate level of reporting. 

You have to build a class to have the utilities to work with Extent report, and while doing so, you have to implement the interface ITestlistener from TestNg; the below code shows how : 

package com.cyborg.core.generic.reportUtils;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.cyborg.core.generic.dataUtils.PropertiesDataUtils;

import io.appium.java_client.android.AndroidDriver;

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.remote.Augmenter;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

public class ExtentReportUtils implements ITestListener {

  String screenShotPath = "";

  static ExtentReports extentReports;
  ExtentHtmlReporter extentHtmlReporter;
  protected ExtentTest extentTest;


  static String pathOfFile = "./configurator.properties";
  PropertiesDataUtils propertiesDataUtils = PropertiesDataUtils.getInstance(pathOfFile);
   Boolean log_to_kibana=Boolean.parseBoolean(PropertiesDataUtils.configDataStore.get("log_to_kibana"));
 
   public void setup() {
     try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date now = new Date();
        String currentTime = simpleDateFormat.format(now);
        extentHtmlReporter = new ExtentHtmlReporter(
              new File(System.getProperty("user.dir") + "_Reports_" + currentTime + ".html"));
        extentHtmlReporter.loadXMLConfig(
              new File(System.getProperty("user.dir") + "/src/test/resources/config/extent-config.xml"));
        extentReports = new ExtentReports();
        extentReports.setSystemInfo("Environment", PropertiesDataUtils.configDataStore.get("Environment"));
        extentReports.setSystemInfo("AppName", PropertiesDataUtils.configDataStore.get("AppName"));
        extentReports.setSystemInfo("ModeOfExecution", PropertiesDataUtils.configDataStore.get("modeOfExecution"));

        extentReports.attachReporter(extentHtmlReporter);
        System.out.println("DONE SETUP FOR extent Report");
     } catch (Exception ex) {
        ex.printStackTrace();
     }
  }

  public void setup(String reportName) {
     extentReports = getExtent(reportName);
  }

  public ExtentReports getExtent(String reportName) {
     if (extentReports != null)
        return extentReports; // avoid creating new instance of html file
     extentReports = new ExtentReports();

     extentReports.attachReporter(getHtmlReporter(reportName));
     return extentReports;
  }

  private ExtentHtmlReporter getHtmlReporter(String reportName) {

     extentHtmlReporter = new ExtentHtmlReporter("./reports/" + reportName + ".html");
     extentHtmlReporter.loadXMLConfig("./src/test/resources/config/extent-config.xml");

     // make the charts visible on report open
     extentHtmlReporter.config().setChartVisibilityOnOpen(true);
     extentHtmlReporter.config().setDocumentTitle(PropertiesDataUtils.configDataStore.get("AppName"));
     extentHtmlReporter.config().setReportName("Regression Cycle");

     // Append the existing report
     extentHtmlReporter.setAppendExisting(false);
     Locale.setDefault(Locale.ENGLISH);
     return extentHtmlReporter;
  }

  public void registerTestMethod(Method method) {
     String testName = method.getName();
     extentTest = extentReports.createTest(testName);

  }

  public void sequenceScreenShot(AndroidDriver driver, String application, String step) {
     try {
        extentTest.addScreenCaptureFromPath(screenshotStepWise(driver, application, step));
     } catch (Exception e) {
        e.printStackTrace();
     }
  }

  public void screenshotAnyCase(ITestResult result, WebDriver driver, String application) {

     String testName = result.getName();
     File file = new File(".");
     String filename = testName + ".png";
     String filepath = null;
     try {
        filepath = file.getCanonicalPath() + "/ScreenShots/" + application + "/" + putLogDate() + filename;
     } catch (IOException e1) {
        e1.printStackTrace();
     }

     if (PropertiesDataUtils.configDataStore.get("run_on_jenkins").equalsIgnoreCase("true"))
        screenShotPath = "job/Cyborg2/" + PropertiesDataUtils.configDataStore.get("build_number")
              + "/artifact/ScreenShots/" + application + "/" + putLogDate() + filename;
     else
        screenShotPath = System.getProperty("user.dir") + "/ScreenShots/" + application + "/" + putLogDate()
              + filename;
     try {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshotFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshotFile, new File(filepath));
        File reportFile = new File(filepath);
        reportLogScreenshot(reportFile, filename, application);
     } catch (Exception e) {
        Reporter.log("Unable to get the screenshot");
     }
  }

  public String screenshotStepWise(WebDriver driver, String application, String step) throws Exception {

     File file = new File(".");
     String filename = step + ".png";
     String filepath = null;
     try {
        filepath = file.getCanonicalPath() + "/ScreenShots/" + application + "/" + putLogDateWithoutmm() + filename;
     } catch (IOException e1) {
        e1.printStackTrace();
     }

     if (PropertiesDataUtils.configDataStore.get("run_on_jenkins").equalsIgnoreCase("true"))
        screenShotPath = "job/Cyborg2/" + PropertiesDataUtils.configDataStore.get("build_number")
              + "/artifact/ScreenShots/" + application + "/" + putLogDateWithoutmm() + filename;
     else
        screenShotPath = System.getProperty("user.dir") + "/ScreenShots/" + application + "/"
              + putLogDateWithoutmm() + filename;
     try {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshotFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshotFile, new File(filepath));
     } catch (Exception e) {
        Reporter.log("Unable to get the screenshot");
     }
     return screenShotPath;
  }

  protected void reportLogScreenshot(File file, String fileName, String application) {
     System.setProperty("org.uncommons.reportng.escape-output", "false");
     String absolute = file.getAbsolutePath();
     if (PropertiesDataUtils.configDataStore.get("run_on_jenkins").equalsIgnoreCase("true"))
        absolute = " /job/Cyborg2/" + PropertiesDataUtils.configDataStore.get("build_number")
              + "/artifact/ScreenShots/" + application + "/" + putLogDate() + fileName;
     else
        absolute = System.getProperty("user.dir") + "/ScreenShots/" + application + "/" + putLogDate() + fileName;
     screenShotPath = absolute;

  }

  public void captureStatus(ITestResult result) {
     if (result.getStatus() == ITestResult.SUCCESS) {
        extentTest.log(Status.PASS, "The test method Named as :" + result.getName() + " is PASSED");
        try {
           extentTest.addScreenCaptureFromPath(screenShotPath);
        } catch (IOException e) {

           e.printStackTrace();
        }
     } else if (result.getStatus() == ITestResult.FAILURE) {
        extentTest.log(Status.FAIL, "The test method Named as :" + result.getName() + " is FAILED");
        extentTest.log(Status.FAIL, "The failure : " + result.getThrowable());
        extentTest.log(Status.FAIL, "StackTrace: " + result.getThrowable());
        try {
           extentTest.addScreenCaptureFromPath(screenShotPath);
        } catch (IOException e) {

           e.printStackTrace();
        }
     } else if (result.getStatus() == ITestResult.SKIP) {
        extentTest.log(Status.SKIP, "The test method Named as :" + result.getName() + " is SKIPPED");

     }

  }

  public String putLogDate() {
     Calendar c = new GregorianCalendar();
     c.add(Calendar.DATE, +0);
     Date s = c.getTime();
     String dateString = new SimpleDateFormat("_EEE_ddMMMyyyy_hhmm").format(s);
     return dateString;
  }

  public String putLogDateWithoutmm() {
     Calendar c = new GregorianCalendar();
     c.add(Calendar.DATE, +0);
     Date s = c.getTime();
     String dateString = new SimpleDateFormat("_EEE_ddMMMyyyy_hh").format(s);
     return dateString;
  }

  public void cleanup() {
     extentReports.flush();
  }

  public void onTestStart(ITestResult result) {

     /*
      * try { DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH-mm-ss"); Date
      * date = new Date();
      */
     /*
      * record = new ATUTestRecorder(System.getProperty("user.dir")+"/videos",
      * dateFormat.format(date), false); record.start();
      *//*
         *
         * } catch (ATUTestRecorderException e) { e.printStackTrace(); }
         */

  }

  public void onTestSuccess(ITestResult result) {

     /*
      * try { record.stop(); } catch (Exception e) { e.printStackTrace(); }
      */

     String testDescription = result.getMethod().getDescription();
     String testCaseNumber = testDescription.split("_")[0];
     String testDesc = testDescription.split("_")[1];
     String status = "PASSED";
     String exceptionType = "NA";
     String detailedError = "NA";
    
     String data ="{\n" +
           "   \"testCaseNumber\" : \""+testCaseNumber+"\",\n" +
           "   \"status\" : \""+status+"\",\n" +
           "   \"testDescription\" : \""+testDesc+"\",\n" +
           "   \"exceptionType\" : \""+exceptionType+"\",\n" +
           "   \"detailedError\":\""+detailedError+"\"\n" +
           "   \n" +
           "}";

     

  }

  @Override
  public void onTestFailure(ITestResult result) {
    
     String testDescription = result.getMethod().getDescription();
     String testCaseNumber = testDescription.split("_")[0];
     String testDesc = testCaseNumber.split("_")[1];
     String status = "FAILED";
     String exceptionType = String.valueOf(result.getThrowable().getClass().getSimpleName());
     String detailedError = String.valueOf(result.getThrowable().getMessage());
    
     String data ="{\n" +
           "   \"testCaseNumber\" : \""+testCaseNumber+"\",\n" +
           "   \"status\" : \""+status+"\",\n" +
           "   \"testDescription\" : \""+testDesc+"\",\n" +
           "   \"exceptionType\" : \""+exceptionType+"\",\n" +
           "   \"detailedError\":\""+detailedError+"\"\n" +
           "   \n" +
           "}";

    
     // TODO Auto-generated method stub

  }

  @Override
  public void onTestSkipped(ITestResult result) {
     String testDescription = result.getMethod().getDescription();
     String testCaseNumber = testDescription.split("_")[0];
     String testDesc = testCaseNumber.split("_")[1];
     String status = "SKIPPED";
     String exceptionType = result.getThrowable().getClass().getSimpleName();
     String detailedError = result.getThrowable().getMessage();
    
     String data ="{\n" +
           "   \"testCaseNumber\" : \""+testCaseNumber+"\",\n" +
           "   \"status\" : \""+status+"\",\n" +
           "   \"testDescription\" : \""+testDesc+"\",\n" +
           "   \"exceptionType\" : \""+exceptionType+"\",\n" +
           "   \"detailedError\":\""+detailedError+"\"\n" +
           "   \n" +
           "}";

  }

  @Override
  public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
     // TODO Auto-generated method stub

  }

  @Override
  public void onStart(ITestContext context) {
     // TODO Auto-generated method stub

  }

  @Override
  public void onFinish(ITestContext context) {
     // TODO Auto-generated method stub

  }
}

Conclusion : With this we are concluding the Selenium Page Object Model framework development through which you can start building the Page Object model framework and can take it to the advanced level , in the upcoming series of the tutorial we will discuss more on the advanced features of Selenium framework . To go through the series of Selenium tutorial you can go through here .

2 Important Selenium design patterns and best practices

In this tutorial we will learn about Selenium design patterns and best practices while working with Selenium Automation framework development (hybrid framework in selenium), there two variations of Framework Design or Framework model that we have to consider, which are : 

We need to know and understand why Language design pattern is required when we are developing our framework in one of the Selenium framework Model. We would suggest to go through the previous segments of the Selenium Framework development tutorial series to get the whole understanding .

Let’s understand that in detail: 

selenium design patterns and best practiceshybrid framework in selenium

While designing any Framework, we need to consider some design architecture, i.e., selenium design patterns and best practices, and as per the need of the type of the framework model, we need to select a Language Design pattern to solve the problem state of the framework design as a whole.

Hence just to conclude, we can choose and Selenium framework model (Hybrid, Page Object Model, Data Driven, etc.), but to implement the model, we need to follow and implement some Language Design Pattern(e.g., java/C# Design patterns ) 

Why We need selenium design Pattern and best practices while building Selenium Framework: 

What design patterns to be used in Selenium Framework : 

There are a few design pattern you could use to implement different areas of the framework, such as an example : 

We will do the live coding template of the whole Framework in the upcoming posts here.

Singleton Design Pattern for hybrid framework in Selenium: 

Singleton Design Pattern is a pattern in which you could create only one object from a class and get to use the same object to access the methods of the class; we could use the design pattern in the configurator where we only need to read the configuration data and can load into some data store(any kind of data structure which you could use as and when required while in the execution from any classes and methods ) 

So we could achieve the same in the below manner while designing the same with Singleton Design pattern. 

NOTE: We will design and develop the framework from scratch in the upcoming section of the tutorial series, but this specific tutorial will provide you insight into the necessity of the design pattern.

package com.cyborg.core.generic.dataUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Properties;
import java.util.Set;

import org.apache.log4j.PropertyConfigurator;


// This is the SingleTon Class 
public class PropertiesDataUtils {

   private Properties properties = null;
   public static LinkedHashMap<String, String> configDataStore = new LinkedHashMap<String, String>();
   InputStream is = null;

// This is the static and private reference of the class which you could use anywhere in you framework 
   private static PropertiesDataUtils propertiesDataUtils = null;
   boolean centralizeLog  = false;


// This is the Private constructor to create the object but you can not access this from outside the class to maintain the design of the SingleTon pattern ie only one object creation .

   private PropertiesDataUtils(String filePath) {
       generateDataStore(filePath);
       centralizeLog =  Boolean.parseBoolean(PropertiesDataUtils.configDataStore.get("centralizedLog"));
       if(centralizeLog)
           PropertyConfigurator.configure(System.getProperty("user.dir")+"//src//test//resources//config//log4j_central.properties");
         else
            PropertyConfigurator.configure(System.getProperty("user.dir")+"//src//test//resources//config//log4j_local.properties");
   }

   private PropertiesDataUtils() {

   }
  
 
// This method basically create the instance of the SingleTon class 

   public static PropertiesDataUtils getInstance(String filePath) {
       if (propertiesDataUtils == null)
           propertiesDataUtils = new PropertiesDataUtils(filePath);
       return propertiesDataUtils;
   }


// this method basically creates the datastore where you want to store all the config data as discussed previously 

   private void generateDataStore(String filePath) {
       try {
           this.properties = new Properties();
           is=new FileInputStream(filePath);
           properties.load(is);
           overrideFromEnvironment();
           Set<Object> keys = loadAllKeys();
           for (Object k : keys) {
               String key = (String) k;
               configDataStore.put(key, getPropertyValue(key));
           }

       } catch (FileNotFoundException fileNotFoundException) {
           String exceptionData = String.valueOf(fileNotFoundException.getCause().getMessage());

       } catch (IOException ioException) {
           String exceptionData = String.valueOf(ioException.getCause().getMessage());
       } finally {
           if (null != is) {
               try {
                   is.close();
               } catch (Exception e) {
                   String exceptionData = String.valueOf(e.getCause().getMessage());

               }
           }

       }
   }


// This method is used to load all the keys from the properties file.

   private Set<Object> loadAllKeys() {
       Set<Object> keys = this.properties.keySet();
       return keys;
   }

   private String getPropertyValue(String key) {
       return this.properties.getProperty(key);
   }
   private void setPropertyValue(String key,String value) {
        this.properties.setProperty(key,value);
   }
  
  private void overrideFromEnvironment() {

     if (this.properties.getProperty("run_on_jenkins").equals("true")) {
        System.out.println("SET run_on_jenkins FLAG TO FALSE IN YOUR PROPERTIES FILE TO RUN LOCALLY....");
        String build_number = System.getenv("BUILD_NUMBER");
        this.properties.setProperty("build_number", build_number);
     }
    
  }
}

By this approach, we could use the Singleton design pattern and use it in our framework.

Factory Design Pattern in Selenium Framework : 

In the factory design pattern, we create a class (we call it a Factory class ), and on the other hand, we have one interface and eventually implemented by “n” number of classes.

The factory class basically returns the object of the above classes (depending on the need), so you don’t have to deal with the above “n” number of classes’ object; rather, you can create one object of the Factory class and call the method of factory class which returns the needed baseline Object for the required classes among the adobe “n” classes.

Now, this design you can consider while creating the different Webdriver / browser implementation. 

We have a various browser and the implementation with a different type of Selenium driver (e.g., LocalDriver, RemoteDriver, ThreadDriver, etc.) and as and when you require a specific type of driver and specific type of browser you can mention in the configuration file and based on the need the factory class will provide you the instance of the driver and browser for your automation script to use further. 

Here is the code base for implementing this design pattern while creating driver -browser interactions : 

Interface Design : 

package com.cyborg.core.web.utils.driverUtils;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;



public interface IDriver {
   public WebDriver init(String browserName);

}


“N” number of browse classes implementation (who are implementing the interface ) :

package com.cyborg.core.web.utils.driverUtils;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.safari.SafariDriver;

public class LocalDriver implements IDriver {
   public WebDriver init(String browserName) {


       String pathToDriver = getDriverPath(browserName);

       if (null != browserName) {

           switch (browserName) {
               case "chrome":
                   System.setProperty("webdriver.chrome.driver",
                           pathToDriver);
                   return new ChromeDriver();
               case "firefox":
                   System.setProperty("webdriver.gecko.driver", pathToDriver);
                   return new FirefoxDriver();

               default:
                   System.setProperty("webdriver.chrome.driver", pathToDriver);
                   return new ChromeDriver();
           }
       } else {
           System.setProperty("webdriver.chrome.driver",
                   pathToDriver);
           return new ChromeDriver();
       }
   }



   private String getDriverPath(String browserName) {

       String osData = System.getProperty("os.name").toLowerCase().split("\\s")[0];
       if (null != osData) {
           if (osData.equalsIgnoreCase("mac")) {
               return "./DriversExe/" + osData + "_" + browserName;

           } else if (osData.contains("nux") || (osData.contains("nix"))) {
               return "./DriversExe/linux_" + browserName;
           } else if (osData.contains("win")) {
               return "./DriversExe/" + osData + "_" + browserName + ".exe";
           }
       }
       return null;
   }
}

Here is the implementation of the Remote Driver class : 

package com.cyborg.core.web.utils.driverUtils;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import com.cyborg.core.generic.dataUtils.PropertiesDataUtils;


import java.net.MalformedURLException;
import java.net.URL;

public class RemoteDriver implements IDriver {

   DesiredCapabilities caps;
   String remoteHuburl=PropertiesDataUtils.configDataStore.get("WEB_GRID_IP");

   @Override
   public WebDriver init(String browserName) {

       if (browserName != null) {

           switch (browserName) {
               case "firefox":
                   try {
                       return new RemoteWebDriver(new URL(remoteHuburl), caps.firefox());
                   } catch (MalformedURLException malformedUrlEx) {

                       malformedUrlEx.getCause().getMessage();
                       malformedUrlEx.printStackTrace();
                   }
               case "chrome":
                   try {
                       return new RemoteWebDriver(new URL(remoteHuburl), caps.chrome());
                   } catch (MalformedURLException malformedUrlEx) {

                       malformedUrlEx.getCause().getMessage();
                       malformedUrlEx.printStackTrace();
                   }
               case "ie":
                   try {
                       return new RemoteWebDriver(new URL(remoteHuburl), caps.internetExplorer());
                   } catch (MalformedURLException malformedUrlEx) {

                       malformedUrlEx.getCause().getMessage();
                       malformedUrlEx.printStackTrace();

                   }
               default:
                   try {
                       return new RemoteWebDriver(new URL(remoteHuburl), caps.chrome());
                   } catch (MalformedURLException malformedUrlEx) {

                       malformedUrlEx.getCause().getMessage();
                       malformedUrlEx.printStackTrace();
                   }
           }
           return null;
       } else {
           return null;
       }
   }

Here is the implementation of the Factory class, which provides the respective browser and driver class object : 

package com.cyborg.core.web.utils.driverUtils;



public class DriverProvider {

   public IDriver getDriver(String typeOfDriver) {


       if (typeOfDriver != null) {
           switch (typeOfDriver) {
               case "local":
                   return new LocalDriver();
               case "remote":
                   return new RemoteDriver();
              
               default:
                   return new LocalDriver();
           }
       } else {
           return null;
       }
   }

}

Likewise, you can implement the Appium driver along with the same design, just provide the implementation and declare a method in the IDriver interfaces. 

Conclusion: With this, we are concluding here how you can use language design patterns as part of the Selenium design patterns and best practices while developing the hybrid framework in Selenium; in the upcoming segments of the tutorial, we will build the Page Object model framework for Selenium Automation.

To get the Overall tutorial on Selenium, you can visit here

Expert Level Selenium Framework 2021

In this tutorial, we will learn exhaustively about the Test Automation framework and design and develop the Selenium framework from scratch to the advanced level.

Let’s break this series of tutorials into multiple modules to accomplish the Selenium Framework Development with Java from concept to advanced level.

Selenium Framework
Automation Framework

Types of the Selenium Framework and their Features

Different types of Selenium Framework are designed and built considering the Application needs that you want to automate. Every different type of test Automation framework is having different features and advantages/disadvantages.

We can classify the Selenium Framework in the below areas :

Test Automation Selenium Framework Features

Keyword Driven Framework in Selenium

What is keyword driven framework?

Keyword Driven Framework in selenium is a Selenium framework built around the feature or design where the Keyword drives the framework; we will see how. 

How Keyword Driven framework Works : 

As mentioned above, KDF is dependent or designed based on Keywords, So what is a keyword? 

Keywords are nothing but the web action words (like click, type, mouseHover, switchFrame etc. ), now you store these keywords in Some repo (or let’s say in Excel files) and for all the keyword’s actions you define a class (which is WebAction utility using Selenium commands ) and write specific methods for Specific Keywords.

Now the next step is basically from your script when you mention let’s say click on some webelement then, in that case, the respective operation goes to the Keyword’s repo (here in our case Excel and then depending on the operation it calls the respective methods which you had defined in the class ).

Additionally, You have different reporting mechanisms (let’s say reportNg or Allure report ) which you can integrate with your Selenium framework to take care of the reporting.

keyword driven framework advantages

keyword driven framework disadvantages 

Data driven framework in Selenium 

What is Data driven framework?

Data Driven framework in selenium is a type of Selenium framework which is built around the feature or design where the data drives the framework; we will see how :

How Data Driven framework Works

Data Driven Framework is designed to handle complex and various type of Data to perform the Automation of the application.

This kind of framework is useful and built where your automation scenarios and use cases must be tested with various sets of data on the same functionalities.

So Data drives the flow of Automation where same test scenarios are tested with respect to different data sets, and DDF should be able to handle various types of Data such as Excel, CSV, YML, PDF, Text, DataBase, Image Data etc.

So you can use TestNG data provider, TestNG XML parameterized Data, JDBC connection manager, PDF data handler, YML data handler. 

You can use Tesseract OCR for working with image data handling.

Data driven framework advantages 

Data driven framework disadvantages

 

Hybrid framework in Selenium Automation

What is Hybrid framework?

Hybrid framework in selenium is a type of Selenium framework which basically is built around the feature or design by taking the concept of both Keyword driven and Data driven framework. 

So, 

Hybrid Framework => Data Driven Framework + Keyword Driven framework.

How Hybrid Framework Works

The hybrid framework supported and driven by Keyword Driven approach with the capability to handle Data driven testing, so both the features are enabled with Keywords repository and their implementation and along with Various Data providers and Dala handlers which is the core feature of the Data Driven Framework.

Page Object Model – Test Automation framework

What is Page Object Model 

Page Object Model framework as the name suggests, is basically a Selenium framework design and developed around the below features and concepts :

Why Page Object Model || Advantages of a page object model

Page Object Model framework design is one of the latest framework model used in the industry, and it comes up with various advance features along with it  

We will see how to design the exhaustive Page Object Model framework here.

Hybrid Page Object Model Selenium framework

Hybrid Page Object Model framework is designed with an approach where its the combination of Data driven Framework and Page Object Model framework.

Here in the Hybrid Page Object Model framework, the Core Design is based on the Page Object model and uses the vast data handler to work with Data-Driven Testing.

We will Design the Hybrid Page Object model Framework here. 

Behavior driven development (BDD) Test Automation framework 

BDD framework is a Selenium framework where the design and the flow of Automation are driven by the behaviour.

What is BDD framework? 

BDD framework is controlled or designed based on the behaviour of the test cases or actions performed. 

In BDD framework, we use English like language called Gherkin language, which is the driving point of the framework. 

Gherkin language is basically in the format of given, when, then (where given narrates a precondition when means when you perform some operation on some webelement like let’s say click operation etc. and then is basically for assertion )

Tools and Technologies required for the Automation Framework

Selenium is an open-source tool, and it does not provide any inbuilt framework along with. Hence you need to design and develop the Selenium framework along with Tools and technologies. 

You could use the tools to work with Selenium framework Development

These are the majorly and frequently used Tools and tech stack to build a robust Selenium framework. 

Conclusion: This tutorial We had an overview of the Selenium Automation framework and what are features of a Selenium framework and what tools are required to build a Robust Test Automation Framework, in the upcoming tutorials we will discuss about the Design Principles and design patterns to build a Selenium framework and eventually we will end up creating a framework hands on which you could use at your own approach. To learn about the whole Selenium tutorial you can visit here and for Critical Selenium Interview Questions click here.

Critical 12 javascriptexecutor methods in selenium

In this segment of the tutorial we are going to discuss javascriptexecutor in selenium in detailed manner and all the probable operations could be performed using javascriptexecutor in selenium in terms of WebAutomation . 

What is javascriptexecutor in selenium 

In the Selenium Library javascriptexecutor is an interface which is being implemented several classes such as ChromeDriver,FirefoxDriver, RemoteWebDriver,EdgeDriver, EventFiringWebDriver, InternetExplorerDriver etc. to support different Javascript related operations towards the respective browser Drivers.

JavaScriptExecutor in Selenium
JavaScript Executor in Selenium

Types of Java Script in Selenium and its Methods: 

There are two different kinds of JavaScript methods are available : 

Difference between executeAsyncScript vs executeScript :

executeAsyncScript  : This type of java script executor is used to execute an asynchronous JavaScript code in the context of the currently selected frame or window.

executeScript : This type of the Java scriptexecutor which basically executes synchronous JavaScript code in the context of the currently selected frame or window. 

 

Operation That could be performed using  javascript executor in selenium : 

There are various crucial Web operations that is achieved executing Javascript in browser driver to achieve certain operation such as : 

Lets discuss all the operation mentioned above : 

Selenium javascript click 

We can perform click operation in Selenium with Javascript operation in the below approach : 

public void jsClick() {
   WebElement element = driver.findElement(By.xpath("Xpath_OF_Element"));
   JavascriptExecutor jscriptExecutor = (JavascriptExecutor) driver;
   jscriptExecutor.executeScript("arguments[0].click();", element);
}

Selenium javascript enter text

We can perform sendkeys operation in Selenium with Javascript operation in the below approach : 

public void jsSendKeys() {
   JavascriptExecutor jscriptExecutor = (JavascriptExecutor) driver;
   jscriptExecutor.executeScript("document.getElementById('id_of_the_element').value='ENTER_THE_TEXT_HERE';");
}

Selenium javascript check checkbox 

We could use option checked=true or false depending on the use-cases to perform the CheckBox operations with Javascript in Selenium.

public void jsCheckBoxOps() {
   JavascriptExecutor jscriptExecutor = (JavascriptExecutor) driver;
   jscriptExecutor.executeScript("document.getElementById('id_of_the_element').checked=false;");
}

Selenium javascript Alert generation

To generate the alert we need to use “alert(‘ALERT_TEXT_TO_BE_SHOWN’);” while performing the operation with Javascript.

public void jsAlertGeneration() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   jscriptExecutor.executeScript("alert('ALERT_TEXT_TO_BE_SHOWN');");
}

Selenium javascript refresh page

To refresh a webpage in Selenium with Javascript Executor we can use history.go(0).

public void jsRefreshPage() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   jscriptExecutor.executeScript("history.go(0)");
}

Selenium javascript to get  inner text of WebPage

To fetch the whole inner text we can use document.documentElement.innerText;

public String jsFetchInnerText() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   return String.valueOf(jscriptExecutor.executeScript("return document.documentElement.innerText;"));
}

Selenium javascript get title of the Page 

To return the title of a Page we can use document.title; along with Javascript Executor in Selenium .

public String jsWebPageTitle() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   return String.valueOf(jscriptExecutor.executeScript("return document.title;"));
}

Selenium javascript to get the Domain 

To pull the domain name we can use document.domain;

public String jsFetchDomain() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   return String.valueOf(jscriptExecutor.executeScript("return document.domain;"));
}

Selenium javascript to get the URL of a webpage

 

To fetch the URL using JavaScript Executor with Selenium we could use document.URL;

public String jsFetchURL() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   return String.valueOf(jscriptExecutor.executeScript("return document.URL;"));
}

Selenium javascript Scrolling a webpage 

We can perform scrolling is multiple ways using Javascript , two of the approaches are shown below in the code snippet such as :

public void scrollIntoView(By locator) {

   try {
       JavascriptExecutor executor = (JavascriptExecutor) driver;
       WebElement element = driver.findElement(locator);
       executor.executeScript("arguments[0].scrollIntoView(true);", element);
       BASE_LOGGER
               .info("scrollIntoView operation has been performed for the locator : " + String.valueOf(element));
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData
               + " while performing scrollIntoView on the element : " + locator);
   }
}

Also we can specify the scrolling value(amount of scroll) like this below approach :

public void jsScroll() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   jscriptExecutor.executeScript("window.scrollBy(0,1000)");
}

Selenium javascript to navigate to a different page

We can navigate to a different webpage/screen by directly providing the url location within the javascriptexecutor in Selenium. 

public void pageNavigationWithJS() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   jscriptExecutor.executeScript("window.location = 'PageURL_To_Navigate'");
}

Selenium javascript To find and click on a hidden element

We could directly click on the hidden element with the Javascript from the backend even though the element is not visible , here is the code snippet for the same:

public void clickOnHiddenElement() {
   JavascriptExecutor jscriptExecutor= (JavascriptExecutor) driver;
   WebElement hiddenElement=driver.findElement(By.id("ID_OF_ELEMENT"));
   jscriptExecutor.executeScript("arguments[0].click();", hiddenElement);
}

Conclusion :

We have so far discussed about the Javascript and various operations to be performed using Javascript executor in Selenium , you are encouraged to go through the full Selenium tutorial to get a better grip on all the different aspects of the same. In the upcoming Segments of Tutorial series we will discuss more on the Selenium Automation Framework and other latest technologies to work with Selenium , and to crack any advanced interview in Selenium you can go through here.

Critical Actions class in selenium -Absolute 2021 guide

We are going to discuss and learn exhaustive usage of Actions class in Selenium across different Web operations . Actions Class in Selenium is widely used to perform various web operations such as mouse and keyboard movement which are advance webbrowser actions.

Actions class in selenium
Actions class in Selenium

Mouse Actions

Keyboard Actions

Actions class in selenium

What is Actions Class in Selenium : 

Actions Class is a class from Selenium Bundle Api from the package org.openqa.selenium.interactions to handle Critical and advance Web interactions with Users through browser Automation. Provides users with a handle to perform various Mouse and Keyboard Actions via different methods mentioned above.  

Actions class in selenium
Actions class in Selenium

We will discuss here all the Web interactions via Actions Class in Selenium, to start with We learn the Mouse Interactions and move towards KeyBoard Interactions with Actions class in Selenium.

Mouse Interactions – Actions Class in Selenium

Drag and drop in selenium

Drag and Drop in Selenium can be done in three different approaches with Actions class in Selenium : 

Drag and Drop in Selenium with Action Class in Selenium via build method : 

We need to have two webelements to perform Drag and Drop in Selenium such as Source WebElement (which is to be dragged) and Destination WebElement (Where the Source WebElement to be dropped, i.e. the Destination WebElement ), The below method is a customized method (which you could use to build your Framework WebUtils) which perform the Drag And Drop in Selenium and this method takes two arguments one is Source WebElement, and another one is Destination WebElement as mentioned previously: 

public void dragAndDrop(By source, By destination) {
   try {
       WebElement sourceElement = driver.findElement(source);
       WebElement destinationElement = driver.findElement(destination);
       Actions builder = new Actions(driver);
       Action dragAndDrop = builder.clickAndHold(sourceElement).moveToElement(destinationElement)
               .release(destinationElement).build();
       dragAndDrop.perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

To learn the whole concept about drag and drop and get to all the approaches to perform Drag and Drop in Selenium, click here.

ClickAndHold in Selenium 

ClickAndHold is another important method from the Actions class (from org.openqa.selenium.interactions package) in Selenium to
first perform left click operation over any webElement and hold it without releasing mouse.

This method is majorly used while performing the drag and drop scenarios, below is the sample code image : 

Actions class in selenium
click and hold -Actions class in Selenium

MoveToElement in Selenium

MoveToElement is a method from the Actions class in Selenium to perform the movement to another WebElement (Destination Webelement), which this method takes as one respective argument.

This method is majorly used while performing the drag and drop scenarios, below is the sample code image : 

Move to element – Actions class in Selenium

Double Click in Selenium

To replicate the double click operation via mouse we need to Perform double click via Actions class in Selenium and we can do it in the below approach : 

public void doubleClick(By locator) {
   try {
       WebElement element = driver.findElement(locator);
       Actions actions = new Actions(driver);
       actions.doubleClick(element).perform();
       BASE_LOGGER.info("Performed the double Click on the Element  : " + locator);
   } catch (StaleElementReferenceException e) {
       BASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
   } catch (NoSuchElementException e) {
       BASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
   } catch (Exception e) {
       BASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
   }
}

The above code snippet is a method which basically takes an argument as Locator, i.e. the WebElement on which the double click has to be performed. 

context click or Selenium right click

To replicate the context click or right click operation via mouse we need to Perform context click method via Actions class in Selenium and we can do it in the below approach : 

public void rightClick(By locator) {
   try {
       WebElement element = driver.findElement(locator);
       Actions actions = new Actions(driver);
       actions.contextClick(element).perform();
       BASE_LOGGER.info("Performed the context Click on the Element  : " + locator);
   } catch (StaleElementReferenceException e) {
       BASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
   } catch (NoSuchElementException e) {
       BASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
   } catch (Exception e) {
       BASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
   }
}

The above code snippet is a method which basically takes an argument as Locator, i.e. the WebElement on which the double click has to be performed. 

Pause in Selenium 

Whenever we want to have introduced any time delay between different Actions we could use the pause method in between the Actions operations, like let’s say if we want to have some few seconds of delay between drag and drop operation, then we can call the pause() method of Actions Class in Selenium in below approach : 

public void pauseBetweenActions(By source,By destination, int timeUnit) {
   try {
       WebElement sourceElement = driver.findElement(source);
       WebElement destinationElement = driver.findElement(destination);
       Actions builder = new Actions(driver);
       builder.clickAndHold(sourceElement).moveToElement(destinationElement).pause(timeUnit).release(destinationElement).build().perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

In the above method it takes three arguments: one source WebElement, another argument is destination element, and the last one is for timeUnit, i.e. the time delay we want to introduce using the pause() in Selenium.

Mouse hover in selenium

Mouse Hover in Selenium operation can be achieved by using Actions class in Selenium, basically, once we are in focus with any webElement and from there, we want to hover your mouse cursor to any other element by this Mouse Hover operation, and this WebElement where we want to take our mouse cursor is called as Target WebElement. 

Below is the code snippet for the same : 

public void mouseHover(By targetedLocator) {
   try {
       WebElement targetedElement = driver.findElement(targetedLocator);
       Actions builder = new Actions(driver);
       builder.moveToElement(targetedElement).build().perform();
       BASE_LOGGER.info("Successfully performed the Mouse hover in Selenium action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing Mouse hover in Selenium ");
   }
}

To learn about all the Selenium webdriver command you can refer here .

Keyboard Actions – Actions Class in Selenium

What is Keyboard actions and where its required :

Keyboard actions means where the operations are directly performed from a keyboard such as lets say we are trying to perform Contrl+A together or Control+C together or performing Key up or Keydown button from keyboard while interacting with WebElements .

We can perform several Keyboard interactions with the help of Actions class in Selenium

sendKeys in Selenium :

We can perform sendKeys operation with the help of Actions class in Selenium in the below manner :

public void sendKeysWithActionClass(By locator) {
        try {
            WebElement element = driver.findElement(locator);
            Actions actions = new Actions(driver);
            actions.sendKeys("KeyBoard Data Entry ");

            // Perform Keyboard Actions ex pressing Control and c together

            actions.sendKeys(Keys.CONTROL);
            actions.sendKeys("c");
            actions.build().perform();
        } catch (Exception e) {
            String exceptionData = e.getCause().getMessage();
           
        }
    }

KeyUp in Selenium :

Similarly we can perform KeyUp operations with the Actions class in Selenium in the below manner :

    public void keyUpWithActionClass(By locator) {
        try {
            WebElement element = driver.findElement(locator);
            Actions actions = new Actions(driver);
            actions.sendKeys("KeyBoard Data Entry ");

            // Perform Keyboard Actions ex pressing Control and c together with keyUp

            actions.keyUp(Keys.CONTROL);
            actions.sendKeys("c");
            actions.build().perform();
        } catch (Exception e) {
            String exceptionData = e.getCause().getMessage();
        }
    }

KeyDown in Selenium

We can perform the keyDown operation with the help of again Actions class in Selenium in the below approach :

public void keyDownWithActionClass(By locator) {

        try {
            WebElement element = driver.findElement(locator);
            Actions actions = new Actions(driver);
            actions.sendKeys("KeyBoard Data Entry ");

            // Perform Keyboard Actions ex pressing Control and V together with keyDown

            actions.keyDown(Keys.CONTROL);
            actions.sendKeys("v");
            actions.build().perform();
        } catch (Exception e) {
            String exceptionData = e.getCause().getMessage();

        }
    }

Conclusion: With these we are done here with the Actions class in Selenium ,In the upcoming tutorial JavascriptExecutor in Selenium in modular yet exhaustive manner . To learn Exhaustively the Selenium command you can refer here also to prepare for Critical Selenium interview questions you can refer here .

Important Selenium webdriver commands of 2021

In this series of  tutorial we will learn about all the exhaustive selenium webdriver commands starting from the very basic selenium commands to the advance Selenium webdriver commands in the below order of articles : 

selenium webdriver commands
Selenium webdriver commands

Basic Selenium Webdriver commands -Questions: 

Intermediate Selenium webdriver commands -Questions:

Advance Selenium WebDriver Commands -Questions:

Selenium basic commands- Answers: 

Selenium navigate to url :

In Selenium Webdriver if we want to navigate or open any specific URL through our browser then we can do it in majorly two different approaches one is with the get() method and another one with navigate , we will take a look at how it could be done : 

public void getUrl(String url) {
  try {
     driver.get(url);
     BASE_LOGGER.info("Successfully navigated to the URL as :  " + url);
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to navigate to URL  : " + url + " with the error as : " + exceptionData);

  }
}

The code you can write to navigate url is driver.get(“http://example.com”) whereas the driver is the Webdriver instance of the Selenium WebDriver interface.

visit here to understand how to launch all browser in Selenium.

How does the get method works internally in Selenium : 

Once this get() method gets called from your test script then Webdriver reference i.e. the driver will wait till the page is loaded , actually the get() method internally triggers onload function which returns the handle to your driver reference once the page is fully loaded.

Selenium navigate forward and navigate back :

Another approach to navigate to the url with the browser history is by using the navigate() method , where the Selenium uses the history of the browser to navigate forward or navigate back with you respective URLs such as : 

Selenium navigate forward

public void navigateForward() {
  try {
     driver.navigate().forward();
     BASE_LOGGER.info("Successfully navigated forward" );
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to navigate with the error as : " + exceptionData);

  }
}

Selenium navigate Back : 

public void navigateBack() {
  try {
     driver.navigate().back();
     BASE_LOGGER.info("Successfully navigated Back to the URL ");
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to navigate Back to URL  : with the error as : " + exceptionData);
  }
}


Selenium refresh page

We can use refresh() method from Selenium navigate 

public void seleniumRefreshPage() {
  try {
     driver.navigate().refresh();
     BASE_LOGGER.info("Successfully done the Selenium Refresh Page ");
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("Unable to perform Selenium Refresh Page : with the error as : " + exceptionData);
  }
}

Selenium click

In order to perform any click operation with Selenium click we have to use method called click() in below approach , there are other ways to perform click operation on any of the WebElement in Selenium ie by using JavaScriptClick which is very useful sometimes depending on situations where your normal Selenium click method is working in a very stable manner , there are some cases where if you are automating with IE browser and  if the Web Application under test is build in some sort of bootstrap JS then normal selenium click method might not work sometime , in those case you could use Javascript click method .

public void safeClick(By element) {
  try {
      driver.findElement(element).click();
     BASE_LOGGER.info("Safeclick operation has been performed for the locator : " + String.valueOf(element));

  } catch (Exception e) {

     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing Safeclick on the element : " + element);
  }
}

You can pass the element using different locator strategies(ie xpath, name, css etc) in the method called findElement() and then perform the click() method operation like above .

Selenium sendkeys

When we need to enter some text in some text box via Selenium we make use of the Selenium sendkeys() method by passing the “Text to be entered ” as the parameter in the method sendKeys(“Text to be entered”) and similar to the click() method this method is also applied to any webElement(here web text box) so we have to use driver.findElement to send the Text to that TextBox .

The Sample code goes like this : 

public void enterTextIntoElement(By element, String textToBeEntered) {
  try {
     driver.findElement(element).sendKeys(textToBeEntered);
     BASE_LOGGER.info(
           "enterTextIntoElement operation has been performed for the locator : " + String.valueOf(element));
  } catch (Exception ex) {
     String exceptionData = ex.getCause().getMessage();
     BASE_LOGGER.error("enterTextIntoElement operation has been failed for the locator : "
           + String.valueOf(element) + " with the exception i.e : " + exceptionData);
  }
}

Selenium clear text field

If we want to clear any data from a previously filled textfield, we can use the method called clear() and also by the help of Keys Class in Selenium we can do so , through which we can take the Keyboard Operations directly along with keyboard shortcuts :

To clear the Data with the help of clear() method we can write in the below approach: 

public void clearField(By element) {
  try {
     driver.findElement(element).clear();
     BASE_LOGGER.info("ClearField operation has been performed for the locator : " + String.valueOf(element));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("ClearField operation has been failed for the locator : " + String.valueOf(element)
           + " with the exception i.e : " + exceptionData);
  }
}

By using the Keys class we can also clear the Text fields in the following approach.

Selenium maximize window

While working with the Browser Automation if we have to Maximize the Window in Selenium then we could use the following approaches : 

Selenium Maximize Window by using Maximize() method :  

public void maximizeWindow() {
  try {
     driver.manage().window().maximize();
     BASE_LOGGER.info("Successfully Maximized the Window");
  } catch (Exception e) {
     BASE_LOGGER.info("Exception Occured while Maximizing the Window As : " + e.getCause().getMessage());
  }
}

Selenium Maximize Window by using ChromeOptions for ChromeBrowser:

By using the below method we are setting a chrome browser instance for Webdriver in maximized mode and the returned driver session will continue to the same feature(ie maximize window )for further web operation as per the script.

public WebDriver openBrowserInMaximizeWindow(){
  try {
     ChromeOptions options = new ChromeOptions();
     options.addArguments("start-maximized");
     WebDriver driver = new ChromeDriver(options);
    
  }catch(Exception e){
     BASE_LOGGER.error("Exception encountered with  : " + e.getCause().getMessage());
  }
  return driver;
}

Selenium minimize window

We can minimize the window using Selenium minimize() command with the following approach :  

public void minimizeWindow() {
  try {
     driver.manage().window().minimize();
     BASE_LOGGER.info("Successfully Minimized the Window");

  } catch (Exception e) {
     BASE_LOGGER.info("Exception Occured while Minimizing the Window As : " + e.getCause().getMessage());
  }
}

Selenium close browser:

To close the browser in Selenium we use close() method in the below approach : 

public void closeCurrentWindow() {
  try {
     if (null != driver) {
        driver.close();
        BASE_LOGGER.info("Successfully closed the current Window/Browser");
     } else {
        BASE_LOGGER.info("Unable to close the current Window/browser instance as Its NULL");
     }
  } catch (Exception e) {
     BASE_LOGGER.info("Exception occurred while closing the current Window/Browser");
  }
}

Selenium quit browser

To quit all the browser instances in Selenium we use quit() method in the below approach : 

public void quitBrowser() {
  try {
     if (null != driver) {
        driver.quit();
        BASE_LOGGER.info("Successfully QUIT Browser");
     } else {
        BASE_LOGGER.info("Unable to QUIT the Browser as Its NULL");
     }
  } catch (Exception e) {
     BASE_LOGGER.error("Exception occurred while QUITING Browser");
  }
}

Difference between driver.close() and driver.quit()in Selenium  :

Intermediate Selenium webdriver commands – Answers:

Dropdown in selenium:

In Webpage DOM structure, the dropdown is implemented by either Select or input Tage of HTML .To work with Dropdown with Selenium and perform certain 

web operations on the dropdowns, we need to use “Select” class from Selenium WebDrivers API as part of “org.openqa.selenium.support.ui” package from Selenium WebDriver. 

There are 2 different problem statement or ask while working with the Selection of DropDown in Selenium : 

Selection of single Element in a Dropdown at a time

In the below approach we can work with Dropdown:  

Step One :

You have to create a handle for the DropDown WebElement using Select class Object creation in the below manner :

Select select = new Select(WebElement webelement);

Step two : 

There are 3 different approaches to select the value from the dropdown in Selenium , we could use any of the below methods to select the value from dropdown in Selenium : 

Here is the below Approach we can take to select value from Dropdown : 

Dropdown in selenium- Approach One : 
In the Approach One you can use the text which is visible of the Desired Selection of the Webelement .

public void selectFromDropDownByText(By locator, String visibleText) {
  try {
     Select dropDownElement = new Select(driver.findElement(locator));
     dropDownElement.selectByVisibleText(visibleText);
     BASE_LOGGER.info("SelectFromDropDownByText operation has been performed for the locator : "
           + String.valueOf(locator));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing selectFromDropDownByText on the element : " + locator);
 }
}

In the above method you can pass the locator of the dropdown and the visible text which you want to select from the dropdown then it will perform the desired operation is Selecting the expected dropdown element . 

Dropdown in selenium- Approach Two :

In this Approach you select the Webelement by using the value attribute  of the desired WebElement’s selection from the dropdown : 

public void selectFromDropDownByValue(By locator, String visibleText) {
  try {
     Select dropDownElement = new Select(driver.findElement(locator));
     dropDownElement.selectByValue(“Desired Webelement’s value ”);
     BASE_LOGGER.info("selectFromDropDownByValue operation has been performed for the locator : "
           + String.valueOf(locator));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing selectFromDropDownByValue on the element : " + locator);
  }
}

In the above method you can pass the locator of the dropdown and the value attribute of the WebElement of which you want to select from the dropdown then it will perform the desired operation is Selecting the expected dropdown element . 

Dropdown in selenium- Approach Three :

In this Approach you select the Webelement by using the index(order of the WebElement in the HTML select tag )  of the desired WebElement’s selection from the dropdown, index generally starts from 0 :

public void selectFromDropDownByIndex(By locator, String visibleText) {
  try {
     Select dropDownElement = new Select(driver.findElement(locator));
     dropDownElement.selectByIndex(5);
     BASE_LOGGER.info("selectFromDropDownByIndex operation has been performed for the locator : "
           + String.valueOf(locator));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing selectFromDropDownByIndex on the element : " + locator);
  }
}

In the above method you can pass the locator of the dropdown and index/order of the WebElement(in the Select Tag of the Dropdown ) of which you want to select from the dropdown then it will perform the desired operation is Selecting the expected dropdown element .

Selection of multiple Elements in a Dropdown at a time 

It depends on the HTML DOM structure and implementation whether any dropdown element is allowed to have multi selection of Elements . To select multiple elements in Selenium we have to follow below two steps : 

Step One : Check whether the DropDown WebElement allows the multi selection by using the method isMultiple() , this returns boolean as true or false.

Step Two : if the above step returns true then the dropdown allows multi selection .And after this we can use the above discussed any/all of the three different approaches to select multiple values and perform any desired operations ..

So to conclude here below is the sample code :

WebElement element =driver.findElement(By.xpath("XPATH OF THE DropDown"));
Select selectMultiple = new Select(element);
if(selectMultiple.isMultiple()){
   selectMultiple.selectByIndex(1);
   selectMultiple.selectByIndex(2);
//Similarly We could use other approaches/method for selecting dropdown elements such as selectByVisibleText or selectByValue
}

Drag and drop in selenium :

In the segment of tutorial we will learn all the different different approaches of performing Drag and Drop in Selenium such as : 

What is drag and drop in Selenium and where its used : 

Drag And Drop is a specific operation when users navigate to your web applications and try to perform operation(dragging by mouse move) on some webelement which can move freely over the application and can be dropped in some other location of the webpage of that application . 

Here the element which is being dragged is called a Source WebElement and the element where it’s being dropped is called a Destination WebElement . 

To Perform the above scenarios via Automation with Selenium we need to drag and drop functionalities provided by Selenium .

Different Approaches of Drag and Drop in Selenium :

Drag and Drop in Selenium using Build() method : 

How Build() method internally works :

build() method from the Actions class in Selenium which is part of the package org.openqa.selenium.interactions internally generates a composite actions 

by combining all the actions which have been called or triggered before calling the build() method.

For an example :

new Actions(driver).clickAndHold(sourceElement).moveToElement(destinationElement)
       .release(destinationElement).build();

The above statement to perform drag and drop operation build is being used to bind the previous actions such as clickAndHold, moveToElement and release methods.

Here is the below code snippet to perform the Drag and Drop in Selenium using build method of Actions class: 

public void dragAndDrop(By source, By destination) {
   try {
       WebElement sourceElement = driver.findElement(source);
       WebElement destinationElement = driver.findElement(destination);
       Actions builder = new Actions(driver);
       Action dragAndDrop = builder.clickAndHold(sourceElement).moveToElement(destinationElement)
               .release(destinationElement).build();
       dragAndDrop.perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

Drag and Drop in Selenium using dragAndDrop() method :

How dragAndDrop() method internally works :

dragAndDrop(sourceWebElement,destinationWebElement) method basically takes two arguments one is source and another one is destination webelement. 
dragAndDrop removes the need of clickAndHold,moveToElement,release methods in Action class, it internally handles all the scenarios which are performed by these methods .

Here is the below code snippet for performing  dragAndDrop with the method dragAndDrop :

public void dragAndDropOps(By source, By destination) {
   try {
       WebElement sourceElement = driver.findElement(source);
       WebElement destinationElement = driver.findElement(destination);
       Actions builder = new Actions(driver);
       builder.dragAndDrop(sourceElement,destinationElement).perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

Drag and Drop in Selenium using dragAndDropBy() method:

How dragAndDropBy(WebElement source, int xOffset, int yOffset) method internally works :

The method dragAndDropBy() takes 3 arguments which are : 

Source WebElement : the Element which is dragged ie the source element 

xOffset : horizontal move offset of the destination location 

yOffset : vertical move offset of the destination location 

Internally this method takes the source webelement and moves and releases it to the destination location. This method is useful if you want to move any source webelement to any pixel locations .

Below is the code snippet for the DragAndDropBy in Selenium :

public void dragAndDropByOps(By source, int xOffSet,int yOffSet) {
   try {
       WebElement sourceElement = driver.findElement(source);
       Actions builder = new Actions(driver);
       builder.dragAndDropBy(sourceElement,xOffSet,yOffSet).build().perform();
       BASE_LOGGER.info("Successfully performed the Drag and Drop action ");
   } catch (Exception e) {
       String exceptionData = e.getCause().getMessage();
       BASE_LOGGER.error("Error encountered i.e : " + exceptionData + " while performing DragAndDrop ");
   }
}

Visit here for the rest of the advanced sets of Intermediate Selenium webdriver commands.

Advance Selenium WebDriver Commands -Answers:

Double click in selenium :

To replicate the operation ie double click in Selenium via mouse we need to Perform double click via Actions class in Selenium  and we can do it in the below approach : 

public void doubleClick(By locator) {
   try {
       WebElement element = driver.findElement(locator);
       Actions actions = new Actions(driver);
       actions.doubleClick(element).perform();
       BASE_LOGGER.info("Performed the double Click on the Element  : " + locator);
   } catch (StaleElementReferenceException e) {
       BASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
   } catch (NoSuchElementException e) {
       BASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
   } catch (Exception e) {
       BASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
   }
}

The above code snippet is a method which basically takes an argument as Locator i.e. the WebElement on which the double click has to be performed.

Contextclick in selenium :

To replicate the context click or right click operation via mouse we need to Perform context click method via Actions class in Selenium  and we can do it in the below approach : 

public void rightClick(By locator) {
   try {
       WebElement element = driver.findElement(locator);
       Actions actions = new Actions(driver);
       actions.contextClick(element).perform();
       BASE_LOGGER.info("Performed the context Click on the Element  : " + locator);
   } catch (StaleElementReferenceException e) {
       BASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
   } catch (NoSuchElementException e) {
       BASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
   } catch (Exception e) {
       BASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
   }
}

For the detailed Advance Selenium webdriver commands visit here.. Also to get understanding of the Actions class in Selenium and its implementations visit here .

Critical FAQs : 

What is manage() in Selenium ?

driver.manage() returns an reference of implementation of WebDriver.Options Interface.Options interface is an interface for managing and handling actions in a browser menu such as : 

For exhaustive sets of Selenium interview Questions -Critical and Advanced sets visit here .

Conclusion :

In this section of the tutorial we covered the Basic Selenium webdriver commands , Click here to learn the Intermediate and Advance Selenium webdriver commands. To learn Selenium from Scratch click here .

71+ UnAnswered Critical Selenium interview questions

In this tutorial of selenium interview questions, we will cover all the critical Selenium interview questions questions along with advanced Selenium Automation framework interview questions .This tutorial is divided into three segments :

Selenium Framework Interview Questions

Advance selenium interview questions

Intermediate selenium interview questions

NOTE : The focus of this Selenium interview Questions and Answers tutorial is to discuss most critical and complex questionnaire as you might already be aware of the basic questionnaires on .

Initially we will start with Advance Selenium Framework interview questions and answers and then move forward Critical/Advanced selenium interview questions and answers and then lastly we finish this tutorial with intermediate levels so that you can prepare well.

Selenium Interview Questions
Selenium Interview Questions

Selenium Framework Interview Questions

Advance Selenium Interview Questions

Intermediate selenium interview questions

Selenium Framework Interview Questions : 

How many popular types of Selenium framework are there?

There are four different types of Selenium framework are there, which are : 

How many different approaches are there to design the Page Object Model framework?

What is Page factory in selenium ?

PageFactory is a class from Selenium library from a package called as org.openqa.selenium.support which helps to design the Page Object Design pattern in the Page Object Model framework, which has few implementations such as :

What is the key design difference between Classic Page Object Model and Customized Page Object Model?

So each webpage should have one interface to store locators and 1 class for the page level web operations and their respect assertions.

What is the design principle of the Page Object Model Framework?

The Design principle of the Page Object Model framework is based on principles or concepts, which are : 

So, All the page actions(different operations of the web page functionality)reside on the respective Page classes.

Mention the key differences among Page Object Model and the Hybrid Page Object Model?

The difference between Page Object Model and Hybrid Page Object Model is that the Hybrid Page Object Model is based on Page Object Model framework Design along with the extensive features of the Data-Driven Framework and supports a wide variety of the Data Operations Utilities such as below : 

What is the language Parser used in the Cucumber -BDD framework?

The language parser used in the Cucumber -BDD framework is Gherkin.

What is the Gherkin language?

Gherkin is DSL (Domain Specific Language) and English like language, which is very much readable and understandable (i.e., give(), when(),then(), etc.)

What do you mean by given() in Gherkin?

 Given () method states that some situation or scenario is given or stated.

 What do you mean by when() in Gherkin?

When () means when you perform some operations.

What do you mean by then() in Gherkin?

then() is used as assertions after the operations are performed by given().when() .

What CI tool do you use as part of the framework?

We use Jenkins (majorly) as an open-source CI tool.

What build tool do you use as part of the framework?

We use build tools such as Maven/Gradle/ant (it was previously used).

What is the key difference between maven and Gradle?

Gradle is the advanced version of what maven perform, and along with that, we can create tasks as well (like the feature that was available in ANT ), so we can consider on a high level : 

Gradle =>> Maven +Ant 

As part of Selenium C#, we use Gallio as a build tool. 

What’s the Unit Test framework that we use as part of the Selenium Automation framework?

We majorly use TestNG/JUnit(JUnit is less used nowadays) as part of the unit test framework while building the Automation framework with Selenium. 

As part of the Selenium C# framework, We use NUnit/MbUnit as a unit test framework.

What approach can be taken into consideration while designing the Reporting tools as part of the Selenium framework?

There is various reporting approach we could take while designing the framework :

Apart from these open-source reporting tools integration, we can also opt for some advanced reporting features or dashboard to build with the below technologies and tools :

How do you use ELK to build the reporting dashboard with Selenium Framework :

There is a basic base design principle which is being used to design the Automation dashboard, which are : 

How do you build an HTML customized report?

You can make use of different listeners and reporters interfaces provided by TestNg to record the events and their respective data sets and create HTML by using those data sets and the HTML tags in the report utils.

What are the challenges that you have faced while developing a framework?

There are different challenges you can mention as per your experience gives while developing the framework, for example : 

Mention which all Selenium components you have used in your Selenium Framework?

You can mention depending on your framework.

What is the flow of your Automation framework?

You can mention the flow of execution of your framework depending on your Framework flow and the tools that you have used; below is an example you can mention :

CI(Jenkins) → Build Tools (Maven/Gradle) → Unit Test Framework (TestNg) → TestNg.xml ->> TestClasses → BaseTest(Every Test Class extends Base class as baseTest where the @beforeClass /@BeforeSuite @afterClass etc exits )–>TestMethods → PageClasses→ Page Methods→ WebUtilities(reusable class for the WebAction utilities )–>> Reporting Utils 

What do you understand by Data-Driven framework, and where do we use a Data driven framework?

A Data-Driven framework is basically a framework that is driven by Data. Having said that, in which the application or the type of the application where the Same Test cases or scenarios is executed several times with the different data sets or the source or Data is very vast like in the case where we need to interact a variety of Data sources there we use Data-driven framework. 

The different Data Source can be : 

How to explain the selenium automation framework in an interview?

 There are different approaches you can take to explain the selenium automation framework in an interview; the best possible approach could be the modular approach, which is to break down the explanation into different separate modules, such as :

Let’s Discuss in Detail : 

Type of the Framework and Key and unique features of the Framework :

You need to mention the type of the framework such as Hybrid Framework, page object model framework, hybrid Page Object Model framework, etc. 

You need to mention the unique features of the framework, such as for example :

Tools and Technologies used in Selenium framework :

You can mention the tools and technologies used while developing the framework, such as :

The flow of the execution of the Selenium Framework :

You can mention the flow of the framework execution, i.e., how do you trigger the test suites and how it flows to the test cases/methods and till the Framework Utils such as webutils, data utils, etc. You can refer to the above question where we discussed how to explain the flow of the execution of the Selenium framework.

Different Critical Scenarios handled by your framework :

In this module, you can discuss the critical features that have been automated as part of your application automation with your framework. There can many use cases or features that you can mention here, such as : 

How to design logging scenarios in the Selenium framework?

You can use log4j for logging, or you can use real-time logging and debugging dashboard implementation with Graylog, which basically uses ElasticSearch in the backend for real-time logging and debugging details.

What are the design patterns you have used while designing the framework?

You can use different Design patterns as per the need and design of the Automation framework, such as :

Critical or Advance Selenium Interview Questions :

How many ways can you run your automation script parallelly?

There are multiple ways and approaches through which you can run your test scripts parallelly, such as : 

Maven :

Using surefire plugin : 

<forkCount>5</forkCount>

 <reuseForks>true</reuseForks>

Here fork count represents the number of parallel threads count.

Gradle : 

tasks.withType(Test) {
        maxParallelForks = Runtime.runtime.availableProcessors()
    }

What is the difference between setSpeed() and sleep() methods?

setSpeed() method in Selenium basically sets the speed of the execution of each and every action/command. 

So let’s say if you setSpeed(“2000”), then every line of execution will be delayed by 2000 milliseconds. 

On the other hand, Thread.sleep() will introduce a 3000 milliseconds delay (it will suspend the thread for the specific operation ). 

Hence sleep() is applied to 1 operation; on the other hand, setSpeed() introduces the delay for each and every operation and thus setting the speed of the execution.  

How to verify the presence of a ScrollBar with Selenium? 

To verify horizontal scroll bar in webpage with Selenium, we use Javascriptexecutor in the below manner : 

JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
Boolean presenceOfHorizontalScroll = (Boolean) javascriptExecutor.executeScript("return document.documentElement.scrollWidth>document.documentElement.clientWidth;");

To verify the vertical scroll bar in WebPage using Selenium webdriver also we need to use Javascriptexecutor

JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
Boolean presenceOfVerticalScroll  = (Boolean) javascriptExecutor.executeScript("return document.documentElement.scrollHeight>document.documentElement.clientHeight;");

Write the code to handle any hidden Web elements in selenium webdriver?

WebElement element=driver.findElement(By.id("id_of_Element"));
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
jsExecutor.executeScript("arguments[0].click();", element);

Mention different approaches to handle a window based pop up using Selenium webdriver?

You can use the below approaches to handle Window based application such as window Pop up : 

What is the parent interface of WebDriver?

SearchContext

Mention the key differences between POI and JXL Jars?

POI supports Conditional formatting, rich text formatting, or xlsx format, but on the other hand, JXL does not support any of these features.

POI library is maintained and updated compared to JXL.

How do you handle your network latencies using Selenium?

We can use the following to handle network latency using in Selenium : 

Driver.manage.pageloadingtime

What are the approaches you would take to handle Ajax content testing with Selenium WebDriver?

AJAX is basically Asynchronous Javascript And XML. All the communication of the AJAX-based Application is based on asynchronous calls, 

which allow any event to be performed without refreshing the webpage. Each operation can be performed independently from other Events.

What are the challenges while working with AJAX calls in Selenium WebDriver?

To work with the AJAX application, you may need to use waits for the above-mentioned use cases : 

What’s the approach to work with Proxy in Selenium Webdriver?

There are two different Approaches you can handle proxy in Selenium Webdriver : 

Proxy proxy=new Proxy();
proxy.setHttpProxy("localhost:8889");
DesiredCapabilities capabilities=new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver=new FirefoxDriver(capabilities);

Mention the ways to achieve synchronization in WebDriver?

We can handle synchronization in Selenium webdriver by using different wait mechanism : 

Mention the key differences between TestNg @BeforeTest and @BeforeMethod ? 

In TestNg @BeforeTest and @BeoreMethod has different aspects, are:

List the different types of WebDriver APIs present in Selenium?

How many ways you can achieve headless execution with Selenium?

We can use the below drivers to achieve headless automation with Selenium: 

What is Fluent Wait In Selenium WebDriver?

With FluentWait, you can set a maximum amount of time(let’s say 3 minutes ) to wait to meet a specific condition, and during that time, you will continuously poll or check with a certain frequency (very small unit of time, let’s say 3 secs )to check.

If the condition is met, then it will return true, and if not, it will throw an “ElementNotVisibleException” exception.

The syntax of fluentwait in Selenium is :

Wait fluentWait = new FluentWait(driver).withTimeout(100, TimeUnit.SECONDS)
  .pollingevery(2, TimeUnit.SECONDS)
  .ignoring(ElementNotVisibleException.class);

Tell us some Selenium exceptions that you have encountered while working with` Selenium WebDriver?

How do you delete cookies in Selenium?

The command to delete the cookies in Selenium is : 

driver.manage().deleteAllCookies();

Explain the approach that how do you read the javascript variable in selenium webdriver?

We need to use JavascriptExecutor to be able to do so. 

JavascriptExecutor jsExecutor = (JavascriptExecutor) webdriver;
String jsVariable = (String.valueOf(jsExecutor.executeScript("return document.title")));

How To Perform Zoom In And Zoom Out Browser operation In Selenium?

We can perform zoom in and zoom out operation in Selenium by using two different approaches, such as : 

Zoom in using Robot class in selenium

Robot robotInstance = new Robot();
//Zoom in

robotInstance.keyPress(KeyEvent.VK_CONTROL);
robotInstance.keyPress(KeyEvent.VK_ADD);
robotInstance.keyRelease(KeyEvent.VK_ADD);
robotInstance.keyRelease(KeyEvent.VK_CONTROL);

Zoom out using Robot class in selenium


Robot robotInstance = new Robot();
robotInstance.keyPress(KeyEvent.VK_CONTROL);
robotInstance.keyPress(KeyEvent.VK_SUBTRACT);
robotInstance.keyRelease(KeyEvent.VK_SUBTRACT);
robotInstance.keyRelease(KeyEvent.VK_CONTROL);

Zoom in using Keys class in selenium

driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,Keys.ADD));

Zoom out using Robot class in selenium

driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,Keys.SUBTRACT));

How to clear a field in selenium without using a clear() method?

We can clear any field without using the clear() method in the below approach : 

We can use the Keys class in Selenium to achieve the same : 

WebElement element = driver.findElement(By.id("id_of_Element"));
element.sendKeys(Keys.chord(Keys.CONTROL, "a"));
element.sendKeys(Keys.DELETE);

How to rerun the failed test cases in selenium?

We can rerun the failed test cases in Selenium in the below two approaches :

With auto-generated TestNG-failed.xml :

After the test execution (ran from testng.xml), TestNG automatically generates TestNG-failed.xml; you can rerun the same XML to run the failed tests ONLY.

By implementing IRetryAnalyzer interface from testNg :

By implementing the interface IRetryAnalyzer we can automatically rerun the failed test cases with TestNg :


If you implement the IRetryAnalyzer you can auto rerun  failed test with TestNg :

public class Retry implements IRetryAnalyzer {
   int counter = 1;
   int retryMaxLimit = 3;
   public boolean retry(ITestResult result) {
       if (counter < retryMaxLimit) {
           counter++;
           return true;
       }
       return false;
   }
}

How to Highlight Element in Selenium WebDriver?

We can use JavascriptExecutor to set the color of the Webelement by mentioning the element.


WebElement element = driver.findElement(By.xpath("id_of_the_element"));
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].setAttribute('style', 'background: red; border: 2px solid red;');", element);

How to double click in selenium?

We can use the Actions class in Selenium to perform the DoubleClick operations in the below manner. The below method takes an argument on which you have to perform DoubleClick.

public void doubleClick(By locator) {
		try {
			WebElement element = driver.findElement(locator);
			Actions actions = new Actions(driver).doubleClick(element);
			BASE_LOGGER.info("Performed the double Click on the Element  : " + locator);
		} catch (StaleElementReferenceException e) {
			BASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
		} catch (NoSuchElementException e) {
			BASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
		} catch (Exception e) {
			BASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
		}
	}

How to scroll in selenium?

We need to use Javascript to perform the scrolling, and the below method provides an advanced approach to scroll into element till the element is visible, which is scroll into view : 

public void scrollIntoView(By locator) {

  try {
     JavascriptExecutor executor = (JavascriptExecutor) driver;
     WebElement element = driver.findElement(locator);
     executor.executeScript("arguments[0].scrollIntoView(true);", element);
     BASE_LOGGER
           .info("scrollIntoView operation has been performed for the locator : " + String.valueOf(element));
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing scrollIntoView on the element : " + locator);

  }

}

How to get all links on the page in selenium?

We can use By.tagName(“a”) to fetch all the links that are available on the page as link refers to the tag called as a; the method goes in the below manner : 

public List<WebElement> getAllLinks() {

  try {
     List<WebElement> allLinks = driver.findElements(By.tagName("a"));
     int numberOfLinks = allLinks.size();
     BASE_LOGGER.info("Number of Links in the Current Page is : " + numberOfLinks);
     BASE_LOGGER.info("GetAllLinks operation has been performed for the Current Page : ");
     return allLinks;
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error("Error encountered i.e : " + exceptionData
           + " while performing GetAllLinks for the Current Page :");
     return null;
  }

}

How to find the number of iframes on a page in Selenium?

We can use the below method to find the number of iframes in a page in Selenium :

public int numberOfIframesInPage() {
  try {
     JavascriptExecutor exe = (JavascriptExecutor) driver;
     Integer numberOfIFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
     BASE_LOGGER.info("Number of IFrames in the current Window are : " + numberOfIFrames);
     return numberOfIFrames;

  } catch (Exception e) {
     BASE_LOGGER
           .error("Exception occurred in Finding numberOfIframesInPage with : " + e.getCause().getMessage());
     return 0;
  }

}

How to switch to default frame in selenium webdriver?

We can use switchTo().defaultContent() method to switch to default frame in Selenium Webdriver: 

public void switchToDefaultFrame() {
  try {
     driver.switchTo().defaultContent();
     BASE_LOGGER.info("Switched to Default Content ");
  } catch (Exception e) {
     BASE_LOGGER.error("Exception Occurred while switching to default Content ");
  }
}

How to handle tabs in selenium?

We can use a List to store all the tabs available and use driver.getWindowHandles() to store the tabs, and once after this, we can handle tabs one by one in the below approach, such as : 

public void switchToTab(int indexOfTab) {

  try {

     ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
     driver.switchTo().window(tabs.get(indexOfTab));
     BASE_LOGGER.info("Successfully switched to tab with tab index as : " + indexOfTab);
  } catch (Exception e) {
     String exceptionData = e.getCause().getMessage();
     BASE_LOGGER.error(
           "Unable to Switch to Tab for :" + indexOfTab + " i.e failed with exception as : " + exceptionData);

  }



}

Intermediate selenium interview questions

Is WebDriver a class or an interface?

Webdriver is an interface where all the driver classes such as ChromeDriver, FirefoxDriver create an object and have reference to the Webdriver interface’s reference.

Which one is faster, XPath, or CSS?

CSS is faster than XPath. 

Why CSS is faster than XPath?

Every browser engine is different, and hence parsing strategy and engine implementation are different through the written XPath. That is why parsing XPath becomes inconsistent at times; for example, IE does not have its own engine implementation to parse XPATH; hence Selenium injects its own native XPath engine to parse XPATH in IE. 

What is heightened privileged browsers?

When the browsers are opened up with some predefined settings (instance with special privileged mode )such as with certain Profiles or Certificates, then it’s called heightened privileged browsers sessions. 

We can launch a browser with Selenium with Profiling or set certificates for the same purposes.

What is headless browser Selenium and how we perform headless browser testing?

  A headless browser is a simulation program for the browser where we don’t have a UI, but we still can run Application under test in invisible mode 

 and perform the desired web operation in the background.

 We use HeadLess browser drivers such as HTMLUNIT driver or phantomJS Driver to perform headless browser testing.

Selenium vs. puppeteer ? 

There are several differences between Selenium and puppeteer (which is a new tool compared to Selenium and developed by Google Chrome DEV)

We will discuss here the comparison between Selenium VS Puppeteer in different aspects : 

HardAssert vs SoftAssert ?

Both the assertion approaches are from TestNg, and each of them has its respective pros and cons

 When you are under the circumstances where you need to have an assertion that’s obvious, i.e., without that step, the remaining steps of the script do not make sense to be executed, then you can put Hard Assert there.

 How to set the window size in selenium?

We can create an object of Dimension class and pass that object to setSize() method : 

Dimension dimension = new Dimension(480,700);
driver.manage().window().setSize(dimension);

What is the version control system you use while working with Selenium?

You can mention whatever VCS you use, such as Github, SVN, etc.

How to clone a git repo?

We can clone the git repo by using :

Git clone repo

How to pull the Git repo code?

Git pull remoteRepoURL branchName

How to push the code to git repo?

Git push remoteURL branchName

How to set the Remote? 

git remote add ProvideARemoteName remoetURL

How to verify the available remotes?

Git remote -v 

How to check which remote URL you currently are in? 

git config --get remote.origin.url

How can you integrate your framework with Jenkins?

As part of the Selenium Automation framework, we are using build tools(such as Maven/Gradle), and we can create a Jenkins Job and connect the Maven/Gradle by providing the configuration with VCS (i.e., Github, etc.)

What are the disadvantages of Sikuli?

How to perform database testing using selenium?

We can perform database testing using selenium in the below modular approach : 

Here is below code snippet for the above steps : 

Selenium Database connection Setup with JAVA JDBC and creates a DB statement : 

   static Connection connection = null;
   private static Statement statement;
   public static String DataBase_URL = "DB_URL";
   public static String DataBase_USER = "DB_UserName";
   public static String DataBase_PASSWORD = "DB_password";



   /* This method Creates the connection with Java JDBC and return it to the Test method to use along with statement 
   */
@BeforeTest
   public void setUp() throws Exception {
       try{

           String dbClass = "com.mysql.cj.jdbc.Driver";
           Class.forName(dbClass).newInstance();
           Connection con = DriverManager.getConnection(DataBase_URL, DataBase_USER, DataBase_PASSWORD);
           statement = con.createStatement();
       }
       catch (Exception e)
       {
           e.getCause().getMessage().toString();

       }


   }

Use the statement to query the DB with SQL : 

@Test
public void test() {
   try{
       String queryData = "select * from TableName";

       ResultSet res = statement.executeQuery(queryData);
       while (res.next())
       {
           System.out.print(res.getString(1));
           System.out.print(" " + res.getString(2));
       }
   }
   catch(Exception e)
   {
       e.getMessage();
   }
}

Closing the Data Connection : 

This step is very important; otherwise, we may end up creating multiple database connections without closing them after the usage, which may cause several issues. 

Here is the code snippet for the same : 

@AfterTest
public void tearDown() throws Exception {

   if (connection != null) {
       connection.close();
   }
}

How to verify the background color and color of a WebElement using Selenium? 

We need to use a method called getCssValue(“color”) for retrieving the colour of a webelement and getCssValue(“background-color”) to pull the background colour of a webelement.

Here is the code snippet : 

String colour  = driver.findElement(By.xpath("XPATH_of_the_Element")).getCssValue("color");

String backgroundColour = driver.findElement(By.xpath("XPATH_of_the_Element")).getCssValue("background-color");

How to verify the font-size of a WebElement using Selenium webdriver? 

We can use the the method called getCssValue(“font-size”)

String fontSize  = driver.findElement(By.xpath("XPATH_of_the_Element")).getCssValue("font-size");

How to verify the font type of a webelement in Selenium Webdriver? 

String fontSize = driver.findElement(By.xpath("XPATH_of_the_Element")).getCssValue("font-type");

How to get tooltip text in selenium?

Getting tooltip text of a WebElement is nothing but getting the title attribute of the Webelement in the below manner : 

public String getToolTipData(By locator){

   WebElement element=driver.findElement(locator);
   return element.getAttribute("title");
}

What is StaleElementException? 

Stale Element means that when a Web element is no longer attached with the DOM/WebPage which was present previously. In that case, Selenium throws a staleelementexception.

This may happen for several multiple reasons like due to AJAX or JavaScript calls which changes the state

of the element makes it unavailable/detached from DOM.  

Conclusion : With these we are done with the Sets of Critical Selenium interview questions covering Selenium Framework interview questions , Read through here to get in depth concepts of Selenium to understand the architecture of Selenium.

Launching Browsers In Selenium-2021 Comprehensive Way

In this segment of tutorial we will be learning how to do Selenium installation and also will be launching browsers in Selenium with hands-on such we will launch Firefox, Chrome, IE browsers and navigate to the Application URL (for an example we will launch www.Google.com to start with). 

In the previous section ie Module one of the tutorial we have learnt about Selenium Architecture , Selenium internal features and functionalities.

Launching Browsers In Selenium
Selenium Tutorial-Launching Browsers In SelenSeium

Selenium Installation: 

To Work with Selenium you have to undergo the following process , which are :

Install Java in the System: 

You can download updated version of JDK from Oracle.com, and install the Java in your system after downloading by following the steps.

Next step is you need to set the JAVA_HOME path from an environment variable (by copying the path of downloaded directories till bin folder)and also update the PATH variable of your system variables.

To validate whether the above steps are done properly go to command prompt and do java – version, it should show you the installed version of the JDK.

Setup IDE, i.e. Eclipse or Intellij:

You can choose your favourite IDE for coding the Automation scripts, Develop the Automation framework, etc., you can choose Eclipse or Intellij community edition for this purposes.

Download the Selenium Webdriver jar file from Selenium Dev.

Setup Selenium in the IDE (Eclipse)

Once you downloaded your favourite IDE, then open that (Eclipse or Idea ) and create a new Java project. Provide a name of the project and create package inside the newly created project, then create a Java class with a proper name (e.g. DemoTest.java, etc.).

Once the above steps are completed then you have to add the Selenium Jar that you have downloaded from Selenium DEV  in the Java Build Path Libraries in Eclipse to work with Selenium in the following way:

STEP 1—> Right-click on the Project, go to the properties option. Click on Java Build Path in the newly opened dialog box.

STEP 2 —> Click on the libraries option and then click on Add External Jars and select your Selenium JARs whichever you have download, in this way you can add any other externally downloaded JAR in your IDE workspace.

Launching Browsers In Selenium Webdriver:

With these above sections we are done the Selenium Installation or Setup process, now in the upcoming section, we will do hands-on Launching Browsers In Selenium with different browsers such as Firefox browser, Chrome Browser, IE browser, Safari Browsers etc. 

How to launch firefox browser in Selenium Webdriver:

To work with Firefox, you would require to download the GeckODriver which is basically the browserdriver for Firefox.

STEP 1 —> Download the geckodriver.exe file from GeckoDriver Github Release Page, while you download the file make sure you download the version based on on your Operating System.  

STEP 2 —> Set the driverbrowser path for geckodriver.

Code Snippets to Launch firefox browser in Selenium java

  System.setProperty("webdriver.gecko.driver", "pathToGeckoDriver exe");
  return new FirefoxDriver();

The above code is for returning the FirefoxDriver , if you want to launch the firefox driver .

Here is the below code in a public static void main format which launch the firefox browser using selenium and also navigate to the web-application under test.

public static void main(String[] args){
    System.setProperty("webdriver.gecko.driver", "pathToGeckoDriver exe");
    WebDriver driver=new FirefoxDriver();
    driver.get("Application URL");
}

How to launch chrome browser in selenium webdriver

Similarly to work with Chrome Browser with Selenium, you have to download the Chromedriver file and set the driver browser path from your script. 

System.setProperty("webdriver.chrome.driver","pathToDriver exe");
return new ChromeDriver();

Again the above code is for returning the ChromeDriver instance if you want to launch the Chrome browser with Selenium.

Here is the below code in a public static void main format which launch the Chrome browser using selenium and also navigate to the web-application under test.

public static void main(String[] args){
    System.setProperty("webdriver.chrome.driver", "pathToChromeDriver exe");
    WebDriver driver=new ChromeDriver();
    driver.get("Application URL");
}

How to launch ie in selenium Webdriver : 

Similarly to work with IE Browser with Selenium you have to download the IE file and set the driver browser path from your script.

Here is the below code snippet for launching IE browser in Selenium:

public static void main(String[] args){
    System.setProperty("webdriver.ie.driver", "pathToInternetExplorer Driver exe");
    WebDriver driver=new InternetExplorerDriver();
    driver.get("Application URL");
}

How to launch safari in selenium Webdriver:

To work with Safari Browser with Selenium you can follow the below code snippet . 

public static void main(String[] args){
    WebDriver driver =new SafariDriver();
    driver.get("Application URL");
}

How to launch edge browser in selenium : 

First Download the Edge Driver Exe file and set the path using System.setProperty like previously what we had done for other browser and then return the edge browser.

Here is the below code snippet for launching the Edge Browser in Selenium 

public static void main(String[] args){
    public static void main(String[] args){
        System.setProperty("webdriver.edge.driver", "pathToEdge Driver exe");
        WebDriver driver=new EdgeDriver();
        driver.get("Application URL");
    }
}

Conclusion: With this Section of the tutorial, we are have learnt how to install Selenium and Launching Browsers In Selenium and open with the Application URL.

How to define Selenium Webdriver architecture-Selenium Tutorial – comprehensive Blackbook 1

We going to start with Selenium tutorial Blackbook in exhaustive and different approach , In this first segment of the Selenium tutorial, we will discuss aboutSelenium Webdriver Architecture, what is Selenium Webdriver , Selenium Webdriver overview, Brief History of Selenium,Advantages of Selenium,limitations of Selenium, Selenium components and some frequently asked questions .

Selenium Tutorial Blackbook
Selenium Tutorial -Module One

What is Selenium Webdriver

Selenium is an open source technology or framework through which we can automate Web based Applications. Selenium Supports Multi browser Testing, Multiple languages like Java, Ruby, Perl, Python is also supported. It supports different multiple platforms like Windows, Linux, macOS etc. as part of the platform.

Brief History About Selenium :

Selenium was initially evolved from an internal tool by Jason Huggins in 2004 at ThoughtWorks.

Later in the year of 2007, Huggins joined the organization Google, and with others like Jennifer Bevan, he continued with the design and development of one of the initial variations of Selenium called Selenium RC. During a similar time period, another person named as Simon Stewart from ThoughtWorks developed an advance web browser automation tools as WebDriver. 

In 2008, a person named as Philippe Hanrigou from ThoughtWorks came up with remote Automation concepts known as “Selenium Grid”.

In 2009, at Google Test Automation Conference, it was decided to merge the two projects, and given the name as Selenium WebDriver, or Selenium 2.0.

Advantages of Selenium Webdriver :

A. Open Source :

Selenium is an open source technology/framework, hence huge community support is available where the development and improvement scope is rapid and vast, also as its open source you can implement any specific feature that you require as part of your work and contribute to the Open source community. 

B. Multi Programming Language supported :

Selenium is supported by widely used languages; it comes up with different programming language bindings, so you can choose your favourable language to work with selenium as per your need and expertise.

Selenium provides support for the below programming languages : 

Java 

C#

Perl

python

Ruby  

Javascript

C. Platform independent :

Selenium is platform-independent, so you can automate your web applications over any platform and any of the Operating System i.e. Windows, Linux, macOS etc.

D. Cross Browser Testing capability

Selenium supports cross browser Testing capability for your web applications; you can run your test suite written with Selenium in multiple browsers such as Firefox, Chrome, IE, Safari etc.

E. Cross Device Testing capability

Selenium Test Automation is used for mobile web application testing automation on various devices such as Android, IOS. 

F. Remote or cloud execution :

Selenium GRID provides you with the feature to run and control your web application’s automation test script in the cloud by making one system as the master node and other system as the slave node, slave nodes connect to one master node, and master node monitors the slave nodes, so your tests are in different slave nodes with the different operating system and different browsers such as Chrome, Firefox, Internet Explorer etc.

G. Parallel Testing capability:

With Selenium, you can achieve Automated Parallel testing capabilities, i.e. you can run your test script or automation Test cases into the different or same browser and different or same operating system in parallel. This feature helps you achieve lesser execution time for the whole Automation Test suite that you have, and also you can test your web application’s feasibility and compatibility with multiple operating system and multiple browsers in parallel.   

H. Compatibility with multiple Framework and third-party tools and technology

Selenium framework can be easily integrated with multiple various third party technologies and frameworks such as different Unit Test framework, i.e. TestNg, JUnit, MbUnit, Nunit etc. etc., different build Tools such as Ant, Maven, Gradle etc., continuous integration tools, i.e. Jenkins, different Test management tools such Jira, testlink etc., various reporting tools such as Allure, Extent Report etc.

I. Headless Browser execution : 

Selenium Webdriver supports headless browser driver for automated test case execution, where all your automation test cases run in headless browser mode, i.e. no browser gets opened and the execution becomes lightning fast so you can complete you Test scripts and the functionality quickly in case of urgent release and validations.

You can basically use htmlUnitdriver or ghost driver for the headless execution with Selenium.  

Disadvantages of Selenium :

A. Native/Window based App Support, not present : 

Selenium is used for Automating Web Bade application, but it does not provide support for native applications or windows based applications.

B. Exhaustive Image-based Automation: 

Selenium does not provide exhaustive support for automating image-based problems or applications, though we can use some third-party tools such as Sikuli, tesseract ocr based solutions which can be integrated with Selenium to do the job related to the Image validations/operations or image data extractions and validations, they are also having some limitations like you may face issues with Parallel testing, identifying handwritten document and validating those in the process of automating your application if there are such use cases.

C. Integration with third-party tools : 

One downside of the integration with multiple third-party tools with selenium is that your automation script might become slower at times.

D. Selenium framework Development :

Designing and developing an advance Test Automation framework with Selenium requires a lot of expertise on selenium and its not too straight forward to build an Automation framework with multiple tools along with Selenium.

E. Browser Specific issues: 

You may face some browser-specific issues while working with Selenium, especially with IE, sometimes you may not be able to handle Web actions like click, sendkeys etc., and the browser may become dead. Hence you need to have advance knowledge to handle those areas while automating Application built on Bootstrap JS and executing it on IE browser.

Also, you might face browser compatibility issues with the Selenium Webdriver versions; you need to make sure you are using the compatible Firefox, Chrome or any other browser you are working with Selenium Webdriver’s version.

F. No official support : 

Like any other Open Source tools selenium is also an open-source tool, which means you will not have official support for your problems like any Paid Tools, even though there is very large community support available, you can work with them with you problem statement, but that can be heavily time-consuming.

Selenium Components : 

Selenium as a tool has the below-mentioned components, which are : 

1. Selenium IDE :

Selenium IDE or Selenium Integrated Development environment is the most initial version of Selenium for Web Application Automation.

Selenium IDE is a kind of record and playback tool, which you can use as a plugin of the browser and record you web action your you applications and that can be saved as a script and later you can run the same recorded script to execute and do validations.

But it has few limitations such as :

A. you need to run the recorded script, modifying the script is not that flexible or neither you can deign you use case and scripts in you own independent approach.

B. Execution is very slow in nature.

C. Majorly supports Firefox, though there are some tweaks you can do to run the recorded script in other browsers such as Google Chrome.

D. parallel execution is not supported.

E. Mobile testing is not supported.

F. Report generation is quite not good.

Its actually very preliminary version of Selenium, by using this you can do very limited Test Automation for your Web Applications.

2. Selenium RC 

Selenium Remote Control is the next version of Selenium and very often its referred to as Selenium 1.0.

How Selenium RC works internally :

Selenium RC consists of two major components, such as Selenium Server, Selenium Client.

The Selenium Server launches the browsers and runs the selenium commands that you have written as a test automation script by using Selenium client libraries available in different languages.

Selenium Server converts the commands/test scripts into something called Selenese commands, and it acts as an HTTP proxy.

Selenium Server interacts with Web Browser engine and performs the Web operation that you are trying to Automate as part of Test cases for the Application Under the Test.

Steps to use Selenium RC : 

A. Install the Selenium-RC Server.

Create a project using your choice of programming language and language specific to the browser driver.

B. Install selenium server

You can set up Selenium Server by simply just download the selenium-server.jar file and run it in your system by using the below command : 

java -jar selenium-server.jar

C. Write the Script by using Selenium client libraries and the same using the Selenium Server.

Limitations of Selenium RC :

  • In Selenium Remote control, automation driver and browser becomes a bit slower reason being browser engine is not directly interacted, rather Selenium RC injects javascript to the browser engine, it also referred to as Selenium Core.
  • The Server which has to be up and running before and during the test script execution.
  • Advance Web actions can not be automated and handled using Selenium RC such as mouse Movement, double click, taking input from Keyboard etc. etc. unlike Selenium Webdriver.
  • Selenium RC does not support Mobile app testing.
  • Selenium RC is dependent on the real browser to run the Automation testing script, and it does not support the headless browser such as HTMLUnitDriver or GHostDriver etc. unlike Selenium Webdriver.

3. Selenium WebDriver:

Selenium Webdriver is the advance version among the Selenium components which is very robust and also supports the advance version of Web interactions and also it does not interact with Browser via Javascript unlike Selenium RC and has the Mobile Application testing support as well. It’s very often referred to as part of Selenium 2.0.

WebDriver can handle dynamic elements and also supports parallel execution with multiple different browsers.

We will have a detailed discussion in the upcoming segments.

4. Selenium GRID : 

Selenium GRID is another component of Selenium through which you can have the remote execution of your automation testing script by creating master-slave nodes. Selenium GRID supports parallel Testing on the same browser as well as multiple browsers. 

We will have further discussion on Selenium GRID in the upcoming sections.

D. WebDriver 3.0: Selenium 3.0 is the latest version of Selenium components which is basically the combination of WebDriver 2.0 and evolution of GRID 3.

In this next segment, we are about to discuss the Selenium WebDriver Architecture in detail, and eventually, it depicts how Selenium works internally,.

Selenium Webdriver Architecture  :

There five major attributes or components as part of Selenium Webdriver architecture : 

    

  • Selenium Client Library or Selenium-Programming language bindings
  • WebDriver protocol or JSON Wire Protocol over HTTP
  • Browser’s Drivers
  • Browsers Engine
  • Browser’s rendering Engine
Selenium Webdriver architecture
Selenium Tutorial-Selenium Webdriver architecture

Selenium Client Libraries or Programming Language Bindings: 

Selenium provides different language binding, i.e. the client libraries to support multiple different languages as part of your Automation Development and Automation test script. For example, Selenium with C#, Selenium with Java, Selenium with Python etc.

WebDriver Protocol or JSON WIRE PROTOCOL :

JSON which basically stands for JavaScript Object Notation. This protocol is also referred to as WebDriver protocol, used for server-client data transfer over the web. Each Browser Driver (e.g. FirefoxDriver, ChromeDriver etc.) has its own HTTP server and uses this protocol to transfer data via Rest Webservices in the form of the HTTP request and HTTP response.

 Browser Drivers:

Each browser has its own browser driver. The Browser drivers establish communication with the respective browser via browser engine. 

When the Automation script gets executed, it directly communicates to browser drivers and eventually with the respective browser. The request and response are transferred via HTTP request and HTTP response.

Browsers Engine :

Every Browser has its own browser engine; The browser engine basically works as an intermediary layer between UI and the rendering engine.

Browser Rendering engine : 

The Browser rendering engine is responsible for displaying the requested document by rendering the specific elements required for the request-response and data.

Selenium Webdriver Architecture and working functionality in a nutshell :

Selenium-WebDriver invokes the browser directly using each browser’s native support for automation and its JavaScript engine. How these calls are being made and the features that they support depend on the browser you are using.

It does not inject JavaScript like Selenium-RC when the browser loads.

The following incidence occurs while running the Webdriver script:

     1. We do the automation scripting using any language binding (Java / C # etc.), and it triggers the WebDriver API while the script is in execution.

     2. The script and eventually commands (eg driver.findElement (By.id (“idName”))) are being converted to JavaScript internally.

     3. Using Browser Engine, it is again converted back to JSON, which is kind of a key-value pair.

     4. After getting the respective value of the respective key, it identifies the respective WebElements and performs the respective user actions (like click, send keys, etc.).

    5. All communication is done using a JSON-Wire or Webdriver Protocol call, and the communications happen over HTTP in the form of Rest API as an HTTP request and HTTP response.

Selenium frequently asked Questions : 

1. What are the types of WebDriver APIs available in Selenium?

Selenium Webdriver is an interface and has different language bindings for different programming languages such as Java, C#, python etc., 

Selenium Webdriver is majorly having two different variants such as : 

A. Selenium Web driver local.

B. Selenium Web driver Remote. 

The Selenium Web driver Local uses the API to work with the specific language binding, and you can work with these with you local execution, while on the other hand if you want to execute you automation testing scripts in Remote, then you need to use the remote Selenium Web driver APIs.

2. Explain What are the scenarios we cannot automate using Selenium?

Selenium does not provide a way to Automate the below areas of aspects of the application, which are : 

A. Performance testing of the Application

B. Security Testing of the Applications.

C. Image-based processing and automation

D. Captcha based automation.

E. Video streaming Scenarios.

F. Native application or window-based applications.

G. Streaming Applications

3. Difference between Selenium 2.0 and Selenium 3.0?

A. For Selenium 2.0 minimum requirement is Java 1.7, on the other hand for Selenium 3.0, the minimum required Java version is 1.8

B. Selenium 3.0 requires GeckOdriver for Firefox version above 47, but this is not the case for Selenium 2.0 

C. Selenium 3.0 supports modern browser such as Edge, Safari etc. but on the other hand for Selenium 2.0, browser driver for Mozilla, Chromedriver, IE which is developed by Selenium developers.

D. In Selenium 3, the support for mobile automation testing got removed, i.e. AndroidDriver and iPhoneDriver, and you have to use tools like Appium for mobile automation testing, which is not the case for Selenium 2.0.

E. Selenium 3.0 doesn’t support the Headless driver, i.e. HTMLUnitWebDriver, but Selenium 2.0 has the support for Headless execution, i.e. with HTMLUnitDriver or ghostdriver.

F. Within Selenium 3, the Selenium WebDriver has become W3C standard; on the other hand, Selenium Webdriver in Selenium 2.0 does not belong to W3C standard.

Conclusion : With this we complete the first segment of Selenium tutorial blackbook covering What is Selenium , Selenium Webdriver Architecture,Selenium overview, Pros and cons of Selenium, In the upcoming segment of Selenium tutorial module 2 we will be discussing about Selenium Installation ie setup , Selenium commands and other basic,intermediate and advance topics of Selenium

Extremely Important 43+ list of TestNg Interview Questions and Answers

In this tutorial we are going to discuss the exhaustive sets of Critical TestNg interview questions and answers and distributed depending on the difficulty level, where you can better equip yourself quickly on TestNg and should be able to clear any TestNg Interview Questions and answers rounds.

These Sets of Testng interview questions are distributed in the following modules or set :

TestNg Interview Questions and answers
TestNg Interview Questions and answers

TestNg Interview Questions – Basic

TestNg Interview Questions – Intermediate

TestNg Interview Questions – Advance

Testng Interview Questions and Answers || Set 1

What is TestNG?

TestNg basically represents “Testing Next Generation” is a unit testing framework that controls the flow and order of test automation and automation scripts by providing various annotations with their functionalities.

What are the advantages of TestNg?

            A. Through Testng’s various annotations, you can control the flow and order of automation and Test execution in a better approach.

            B. Test Classes or Test script Methods parallel execution can be achieved with TestNg.

           C. TestNg can be easily integrated with different build tools such as Maven, Gradle. Also, it can be integrated with CICD tools such as Jenkins.

           D. TestNG provide details HTML reporting feature and easily integrated with other Test reporting platform such as Allure, Extent Report with features of TestNG Listeners.

          E. All the tests can be triggered by the testng.xml file where you can mention the Test class/Test/Test Package name to be run.

          F. Data driven Testing can be done with the TestNg DataProvider annotation. Also, parameterization Tests can be done through Testng.xml as well, such as while performing cross browser testing, you can parameterize the different browsers for different tests. This feature helps to build the Data Driven Framework with TestNG.

         G. TestNg Provides a way to include/exclude a set of a test from tesngNg.xml with include and exclude attribute.

         H. With TestNg, you can group your tests and dependency injection in between the tests.

         I. TestNg provides many listeners with those you can achieve a lot of things like you can do custom reporting(IReporter), integration with different tools(ITestListener), Change the behavior of TestNG Test annotation in runtime with IAnnotationTransformer and many more.

        J. You can skip the specific test, prioritize your test order, create a time-bound test with TestNg Test annotations.

        K. You can use Hard Assertion as well as Soft Assertion with TestNg for writing Assert statement.

        L. TestNg generates TestNG-failed.xml after each Test execution, so you can you the same generated TestNG-failed.xml to rerun your failed test scripts.

       M. TestNg provides various Test annotation such as @BeforeMethod, @AfterMethod, @BeforeTest, @AfterTest.@BeforeSuite,@AfterSuite.

       N. You can run the expected exception Test with TestNg.

       O. You can rerun the failed test with IretryAnalyzer of Testng 

How do you trigger and execute the TestNg test Script?

You can run TestNg Test script in several ways : 

      A. Right Click on Test Class and “run as” and select the option of “TestNg Test.”

      B. Create testng.xml and right on the file and run the xml file.

      C. If you integrate testNg.xml with the build tool such as Maven/Gradle, then you can run from maven or Gradle as well.

      D. If the build tool such as Maven/Gradle is integrated with CICD, then you can run from CICD, i.e., from Jenkins.

State the Testng annotations that are available ?

Majorly used Testng Test annotations are :

@BeforeSuite

@AfterSuite

@BeforeTest

@AfterTest

@BeforeClass

@AfterClass

@BeforeMethod

@AfterMethod

@BeforeGroups

@AfterGroups

@Test

Mention the TestNg annotations execution sequence?

From the Test execution standpoint here is the below sequence for all the available TestNg annotations :

Precondition Annotations :

@BeforeSuite

@BeforeTest

@BeforeClass

@BeforeMethod

Test Annotations :

@Test

PostCondition Annotations: 

@AfterSuite

@AfterTest

@AfterClass

@AfterMethod

How to disable test execution for a test script?

You can use enabled attribute is equals to false in the @Test annotation attribute like mentioned below :

@Test(enabled = false)
public void logout(){
   System.out.println("Sample Test");
}

How can you specify listeners in TestNG xml?

You can use Tesng xml file for mentioning the listeners to be used as part the test script executions, in the below approach:

<suite>

<listeners>

        <listener class-name=”org.uncommons.reportng.HTMLReporter” />

        <listener class-name=”org.uncommons.reportng.JUnitXMLReporter” />

</listeners>

What is the Timeout Test in TestNg?

In this case, the “timeout test” means, if in case the test script takes longer than the specified time period to execute, then testng will abort the test and will mark as a failed test.

@Test(timeOut = 6000) // this time in mulliseconds
public void testShouldPass() throws InterruptedException {
   Thread.sleep(2000);
}

How to achieve the Expected Exception Test with TestNG?

If a Test method throws an exception, which is the same as specified as part of the test annotation expectedExceptions attribute, then TestNg would mark the test as passed.

@Test(expectedExceptions = ArithmeticException.class)
public void TestDivision() {
   int i = 1 / 0;
}

 The above Test method will be passed as it throws the exception expected by TestNG.

What is the difference between @BeforeTest and #@BeforeMethod annotation?

@BeforeTest is executed once before each of the testng <test> tag mentioned in the testng.xml file 

@BeforeMethod is executed before each and every test script method.

What is the advantage of using the testng.xml file?

With the testng.xml file, you can control the flow of execution with single test suite or multiple test suite in a single testng xml file. Some of the important features are :

A. testng.xml file allows us to exclude and include test methods and test group execution.

B. You can pass test data/parameters through testng.xml.

C. You can add dependency between test methods and also a group of test methods

D. You can prioritize the test cases.

E. Parallel test execution of test cases is achieved.

F. You can implement different testng listeners and use them by mentioning those in the testng.xml.

G. If you run your suite with testng.xml, then you will only fail the test for the next iteration by using TestNG-failed.xml is generated after every execution.

H. You can run specific groups of tests using <groups>tag of TestNG xml.

How many types of dependencies can you achieve by using TestNG?

There are two types of dependencies we can achieve with TestNG : 

A. DependsOnMethods : 

By using this dependsOnMethods attribute, you are defining which test method will be dependent on other test methods, So if the depending method is failed or not run, then the dependent test method also will not run.

@Test
public void loginUserProfile() {
   System.out.println("Login user ");
}
@Test(dependsOnMethods = "loginUserProfile")
public void logOutPage_user() {
   System.out.println("Logout page for User");
}

 Here is logOutPage_user test method that will run after the successful execution of the loginUserProfile test.

B. dependsOnGroups : 

In this type of test dependency, It allows us to put the dependency injection for the test methods with a group of test methods.

The flow of execution happens in such a way ie the testGroup first gets triggered and executed and then the dependent test method gets triggered, and once after successful completion of the group test, the dependent test method will get executed.

@Test(groups="AtestGroupName")
public void testcaseOne()
{
   System.out.println("testcaseOne in process");
}
@Test(groups="AtestGroupName")
public void testcaseTwo()
{
   System.out.println("testcaseTwo in process");
}
@Test(dependsOnGroups="AtestGroupName")
public void testcaseThree()
{
   System.out.println("testcaseThree in process");
}

Testng Interview Questions and Answers || Set 2

What is meant by invocationCount in TestNG?

invocationCount is a test annotation attribute by which you can define the number of iteration the test method will be executed in a single execution. 

@Test(invocationCount = 2)
public void testOfInvCount() {
   System.out.println("Invocation count test in progress");
}

 The above test will execute two times as invocationCount is mentioned as 2.

What are listeners in TestNG?

in TestNg the listeners are basically interface in Java which you need to implement in your class. The implemented class will keep on listening to certain events and executes the specific block of code associated with that event.Here when you implement the interface you ultimately implement the unimplemented methods and those block of code or the methods will get executed as and when specific event gets triggered. 

With the help of TestNG listeners, we can perform a lot of run time actions by listening to a different event triggered by the test script execution and their status, or we can do reporting. Also, we can change the implementation of TestNg annotation.

Mention the differences between @Factory and @Dataprovider annotations in TestNg?

@Dataprovider: When you want to execute the same test, but with different diverse sets of data in every run, you can use the dataprovider annotation, and this you can achieve the datadriven testing approach. Here the test method execution happens using the same class instance to which the test method belongs.

@Factory: This will be executed all the test methods present inside a test class using separate and multiple instances of the class.

How to use TestNG Reporter Class for the log generation?

You can log the details and data using the Reporter class, and these logs will be captured by the report generated by TestNG

Reporter.log(” Logging message “);

How to do exception handling in TestNG?

You can mention the type of expected exception in an attribute called expectedExceptions with the @test annotation; in this case, then TestNg would mark the test as passed.

@Test(expectedExceptions = numberFormatException.class)

How to achieve dependency injection via TestNg XML ?

TestNG allows us to inject dependencies between different groups of tests via the TestNG XML file. Through which we can have the dependence of one group onto another.

What are the various assertion approaches for TestNG ?

We can use two types of assertions with TestNg. 

Soft Asserts

Hard Asserts 

Mention some of the commonly used assertions with TestNG 

Some of the widely used assertion methods in TestNG :

  • assertEquals(boolean actual,boolean expected)
  • assertEqual(String actual,String expected)
  • assertEqual(String actual Result,String expected Result , String message)
  • assertTrue(condition)
  • assertFalse(condition)
  • assertFalse(condition, message)
  • assertTrue(condition, message)

What do you understand by the asserts in TestNG?

An assertion is performed to validate the actual test results with respect to the expected test results. In TestNg, we can use hard assert of soft assert. 

Difference between Hard assert and soft assert in TestNg

While working with the Hard assert, If in case we get any failure in the assertion condition then the subsequent test steps will not be executed and would be aborted, and eventually the test will be marked as a failed test case. 

While on the other hand the Soft Assert takes into considering of validating all the assertion points even if there are any failures in any of the assertions . That means the test execution does not get aborted even if one assertion fails.

How to write soft assertion in TestNg 

The below piece of code gives the approach of writing the soft assertion in TestNG

 @Test
   public void assertion() {
   SoftAssert softAssertion = new SoftAssert();
   //Assertion 1 
   softAssertion.assertEquals("exp", "act");
   //Assertion 2 
   softAssertion.assertEquals(123, 123);
   //Assertion 3 
   softAssertion.assertEquals("actual Value", "expected value");
   // At the end considering all the assertion values
   softAssertion.assertAll();
}

How to use regular expression in TestNG groups?

A regular expression can be used in TestNG to execute the groups which have a similar pattern in their naming. 

For example, if you want to run all the groups starting with “testX” as per the name is concerned, then you can use the regular expression as testX.* in the TestNG XML file.

Testng Interview Questions and Answers || Set 3

How do you exclude a group from the test execution cycle?

You can use exclude tag to exclude a group of test case from executing in the below manner in Testng xml file 

<groups>

    <run>

        <exclude name = “excludeDummy”>

        </exclude>

    </run>

</groups>

What are the types of reports generated in TestNG by default?

TestNG generates two kinds of reports after the execution, which are :

Mention the difference between the TestNG test suite and the TestNG test?

TestNG test suite is the collection of test classes and test methods that can be run simultaneously as well as parallelly from the TestNG XML file. 

On the other hand, the TestNG test method is a single test case file or test method.

What is the use of threadPoolSize attribute with the @Test annotation 

Through The threadPoolSize attribute we can define a thread pool with the specific mentioned size by the number for the testmethod to be executed via multiple available threads.

The attribute is being ignored if the invocationCount is not being mentioned.

 @Test(threadPoolSize = 3) 
   public void testCaseOne(){
      System.out.println("testCaseOne in process");
   }

In the above test method,testCaseOne will be invoked from the three different threads.

What does alwaysRun attributes do?

This alwaysRun annotation attribute is used whenever you want to execute the test method irrespective of the dependent parameters on which the test method depends, fails. If you set to true then you need to set the attribute is true.

What are the different listeners that are available?

ITestListener

IReporter 

ISuiteListener

IAnnotationTransformer 

IAnnotationTransformer2

IHookable 

IInvokedMethodListener 

IMethodInterceptor 

What is default value for the TestNG Priority?

The TestNG priority has the default value is zero.

How to re-run TestNg Failed Tests using Auto Retry mechanism ?

TestNg provides one interface called as IRetryAnalyzer listener which you can implement the interface auto re-run your Failed Test scripts by mentioning the class in the testNg.XML file , Here is the below code for implementing the same :

TestNg Auto Retry Failed Tests
Testng interview questions and answers- TestNg Retry Test Script

In the above area you can configure the number of re-try ,maximum counts and also you can mention in which all exceptions you want to re-run Test scripts.

Approach Two : How to re-run TestNg Failed Tests using Auto Retry mechanism

In the below approach you can build 2 classes ie one is Retry class where you can keep the logic of controlling the number of iteration in case of test failures which will implement the interface Testng IRetryAnalyzer.

Another class is basically which will implement the another interface listener IAnnotationTransformer and implement the method transform which internally interacts with the previous class (ie Retry class)

public class Retry implements IRetryAnalyzer {

    int retryCounter = 0;
    
    // The maximum number of failed execution 
    int autoRetryLimit = 2;

    @Override
    public boolean retry(ITestResult iTestResult) {
        if (retryCounter < autoRetryLimit) {
            retryCounter++;
            return true;
        }
        return false;
    }
}

public class CognitiveRetry implements IAnnotationTransformer {


    public void transform(ITestAnnotation annotation, Class testClass, Constructor testCons, Method tMethod){
        IRetryAnalyzer retryAnalyzer=annotation.getRetryAnalyzer();
        if(retryAnalyzer==null){
            annotation.setRetryAnalyzer(Retry.class);
        }
    }
}

and finally add the CognitiveRetry class in the listener for testng.xml file .

<listeners>
    <listener class-name= "com.lambdageeks.cognitiveRetryUtils.CognitiveRetry"/>
</listeners>

How to achieve TestNG itestlistener implementation?

ITestListener is an interface in TestNg which has multiple methods(unimplemented since its an interface) which can be implemented by a class . Each method represents specific functionalities or scenarios , hence depending on your need you can implement those methods .

For an example onTestFailure is a method which you can implement where you want to perform any operations while any test method gets failed , lets say you want to capture the screenshot while in case of any test method failures , so you can write the takescreenshot method inside the onTestFailure , and as the ITestListener is an interface hence testNg will keep on listening on the events (test failures) and whenever there is test failures your screenshot will get captured .

Here is the implementation of capturing screenshot whenever you test script encounters a failures :

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

public class CustomListerners implements ITestListener {

    WebDriver driver=null;
    String filePath = "D:\\LambdaGeeks\\SCREENSHOTS";
    @Override
    public void onTestFailure(ITestResult result) {
        String testMethodName=String.valueOf(result.getName()).trim();
        ITestContext testContext = result.getTestContext();
        WebDriver driver = (WebDriver)testContext.getAttribute("driver");
        captureTheScreenShot(testMethodName, driver);
    }

    public void captureTheScreenShot(String methodName, WebDriver driver) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        /*
        Each screenshots will get saved with along with the test Name to have better correlation
         */
        try {
            FileUtils.copyFile(scrFile, new File(filePath+methodName+".jpg"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void onFinish(ITestContext context) {}

    public void onTestStart(ITestResult result) {   }

    public void onTestSuccess(ITestResult result) {   }

    public void onTestSkipped(ITestResult result) {   }

    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {   }

    public void onStart(ITestContext context) {   }

}

And also you need to add this class in listener tag in testng.xml file like we had done in previous question.

How to Implement testng iAnnotationtransformer ?

TestNg provides an interface named as IAnnotationTransformer that provides a method called  “transform” which you can implement and would be triggered in runtime by TestNG , this implementation is used to modify the test annotation behavior of the test class and test methods

In the below segment we would see how we could do that

public class TestClassAnnotations {

    @Test(alwaysRun = true,dependsOnMethods = "testMethodB")
    public void testMethodA() {
        System.out.println("--- Customizing the runtime behavious with ITestAnnotation ---");
    }

    @Test
    public void testMethodB() {
        System.out.println("--- Second TestMethods ---");
        Assert.fail();
    }

}

By default if we run the above code then only one method will get executed which is testMethodA and another method testMethodB will fail because we are intentionally failing this by usinig the Assert.fail() method.

But if we change the Alwaysrun=true annotation to false by using the IAnnotationTransformer then this method will not get executed , below is the code snippet on how to implement the IAnnotationTransformer and use it in the testing.xml to change the behavious of the TestNG annotation

The implementation of the CustomAnnotationTransformers goes here :

public class CustomAnnotationTransformers implements IAnnotationTransformer {

    public boolean isTestRunning(ITestAnnotation iTestAnnotation) {
        if (iTestAnnotation.getAlwaysRun()) {
            return true;
        }
        return false;
    }


    public void transform(ITestAnnotation annotations, Class testClasses, Constructor testConstructors, Method testMethods) {

        if (isTestRunning(annotations)) {
            annotations.setEnabled(false);

        }

    }

}

Here is the listener we need to add in testing.xml file

<listeners>
    <listener class-name= "com.lambdageeks.CustomAnnotationTransformers"/>
</listeners>

How to implement testng iinvokedmethodlistener?

If you want to implement a feature where a some certain method will gets executed before and after each and every Test method of TestNg then that feature could be implemented by the testng IInvokedMethodListener listener.

 

Here is the code snippet to implement the features :

package com.lambdageeks;

import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;


public class CustomAnnotationTransformers implements IInvokedMethodListener {

    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {

        System.out.println(" ::: Before Method from IInvokedMethodListener is Triggered for the Test Method named as :  " + method.getTestMethod().getMethodName() + " ::: ");
    }

    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {

        System.out.println(" :::: After Method from IInvokedMethodListener is Triggered for the Test Method named as :  " + method.getTestMethod().getMethodName() + " ::: ");

    }
}

Here is the Test Class for testing the feature :

public class TestClassAnnotations {

    @Test(alwaysRun = true)
    public void testMethoddummy() {
        System.out.println("--- This is a test Method , testing the feature of IInvokedMethodListener Testng Listener  ---");

    }

}

You have to Mention the TestNG iinvokedmethodlistener in the listener tag in the testng.xml like always

<listeners>
    <listener class-name="com.lambdageeks.CustomAnnotationTransformers"/>
</listeners>

The output of the execution would look like this :

::: Before Method from IInvokedMethodListener is Triggered for the Test Method named as :  testMethoddummy :::

— This is a test Method , testing the feature of IInvokedMethodListener Testng Listener  —

 :::: After Method from IInvokedMethodListener is Triggered for the Test Method named as :  testMethoddummy :::

How to implement Data providers in TestNG?

We can implement the DataProvider using TestNg in the below approach :

public class DataProviderDemo {

    @DataProvider(name = "dpName")
    public Object[][] dataProvidersMethodName() {
        return new Object[][]{{"Lambda"}, {"Geeks"}};
    }

    @Test(dataProvider = "dpName")
    public void dataproviderDummyTestMethod(String dataValues) {
        System.out.println("The Data Params with data provider examples : : " + dataValues);
    }
}

If we don’t set the priority of the test method in which order the tests are executed in TestNG?

The tests are executed in the order of Alphabatical order of the TestmethodName..

 

Such as in the below code snippet :

public class SequenceTest {

    @Test()
    public void geeks() {
        System.out.println("Sequence Test , Method ran :geeks ");
    }

    @Test()
    public void lambda() {
        System.out.println("Sequence Test , Method ran : lambda ");
    }

    @Test()
    public void abc() {
        System.out.println("Sequence Test , Method ran :abc");
    }
}

The output would look like this :

Sequence Test , Method ran :abc

Sequence Test , Method ran :geeks

Sequence Test , Method ran : lambda

 

How to run your Test scripts in parallel ?

You can run your Test scripts using TestNg XML file by mentioning the parallel=”methods” thread-count=”2″, here 2 parallel cases will get executed , if you want to executed more threads in parallel.

<suite name="DummyTest" parallel="methods" thread-count="2" >

<listeners>
<listener class-name="org.uncommons.reportng.HTMLReporter" />
<listener class-name="org.uncommons.reportng.JUnitXMLReporter" />
</listeners>
</suite>  

How to integrate TestNg with GRADLE build Tool?

You can run Testng Suite in gradle in different ways:

How to run TestNg Groups using Gradle : You can create a Task in build.gradle file can mention the useTestNG() and mention the below details while running the Test Groups.

TestNg Interview Questions and Answers-TestNg with Gradle

How to run Testng Default listener with Gradle to generate report using TestNg library

TestNg Interview Questions and Answers- Testng With Gradle Default Listeners
TestNg Interview Questions and Answers- Testng With Gradle Default Listeners

If you want to use the custom listener then you can mention that same in the following approach :

TestNg Interview Questions and Answers-TestNG Custom Listeners with Gradle
TestNg Interview Questions and Answers-TestNG Custom Listeners with Gradle

How to run Testng Runner xml file using command prompt ?

You can use TestNg Downloaded location and mention org.testng.TestNg.testNgRunner.xml to run the runner xml file from the command prompt.

java -cp "/opt/testng-7.1.jar:bin" org.testng.TestNG testngRunner.xml

How to Integrate TestNg XML with Maven ?

You can integrate TestNg with Maven with the use of Plugin called maven-surefire-plugin where you can configure to run the testNgrunner.xml file using the configurations :

TestNg Interview Questions and Answers-TestNg-Maven-Surefire Integration

How can you specify the TestNg Test parameter using TestNg and Maven ?

You can specify the Test parameter using Maven SureFire Plugin with TestNg.XML file in the below fashion

TestNg Interview Questions and Answers-Test Parameter

Conclusion : With this we conclude the list of all critical and important TestNg interview questions and answers , to get better grip on TestNg you can go through the exhaustive documentation on TestNg.

To learn more about the exhaustive Selenium tutorial you can visit here.