The Puppeteer is an open-sourced java framework which is developed with node-js library. The Puppeteer has the ability to work as a web scraping tool. It can be also used as a test automation for web based applications just like selenium web driver. The popularity of Puppeteer is getting increased rapidly for test automation. The pre-requisites to walk through the Puppeteer Tutorial, are basic knowledge of command line, JavaScript, OOPs concept and HTML DOM structure. The complete Puppeteer tutorial is distributed into topics which are mentioned in the below table of content.
In this article of Puppeteer Tutorial, we will explain about Puppeteer Overview and Puppeteer Environment Variables.
Puppeteer Overview
The Puppeteer is an open-sourced java framework which is developed with node-js library. Puppeteer is able to control Chrome browser over the devtool protocol with the help of the high-level application interface(API). The Puppeteer is able to control both headful and headless chrome browsers.
The Puppeteer framework is introduced by Google. As per the functionality, it’s not a new concept. But it make the work easier. Fundamentally, it summaries a list of activities through a compacted package.
How do Puppeteers work?
Puppeteer uses the Node JS library.
The Node JS allows to use the high-level APIs.
The APIs are capable of controlling the Chrome browser over devtool protocol.
By default, Puppeteer works with headless Chrome browsers but it can interact with headful Chrome browsers as well by changing the default configuration.
Chrome DevTools Protocol:
Using the Chrome DevTools Protocol, tools like Puppeteer are able to instrument, inspect, debug and profile the blink-based browsers such as Chromium, Chrome, etc.
Here, the instrumentation of the browser is divided into a number of domains such as DOM, Debugger, Network, etc. The every domain explains all the different supported commands and the generated events.
Features of Puppeteer:
The manual processes through the Chrome browser can be automated.
It can captures screenshot of any web page and generates the image or pdf file of the screenshot.
A single page application can be developed of server side rendering using the Puppeteer.
It can automate the web form submission, UI testing, keyboard input, etc., with checkpoints.
It provides more control over the Chrome browser.
The default headless mode is very fast.
It supports web scraping.
Ability to measures rendering and load timing using Chrome performance analysis tools.
Puppeteer vs Puppeteer-core:
Since Puppeteer version v1.7.0, below two packages, are available in every release –
puppeteer-core package
puppeteer package
Puppeteer-core Package:
Puppeteer-core is a java-base Node library that is able to perform any operation that supports the DevTools protocol. The Puppeteer-core doesn’t download Chromium during the installation. As a library, Puppeteer-core is completely driven through its programmatic interface. Also, the features of Puppeteer-core can’t be customized by all PUPPETEER_* env variables. The basic command to install Puppeteer-core –
npm install puppeteer-core
# or "yarn add puppeteer-core"
When using puppeteer-core, include statements will be looks like below –
const puppeteer = require('puppeteer-core')
When to use Puppeteer-Core:
To develop Puppeteer project to use existing Chrome browser over the DevTools protocol where additional chromium download is not required.
To develop another end-user product or library on top of DevTools protocol. For example, one project may build a screenshot generator using puppeteer-core and write a custom setup.js script that downloads headless_shell instead of Chromium to save storage.
Puppeteer Package:
Puppeteer is a complete product for Chrome or Chromium browser automation. During the installation, it downloads the latest version of Chromium, and after that, it was driven by puppeteer-core. As an end-user product, Puppeteer supports all the PUPPETEER_* env variables to customize its behavior. The basic command to install Puppeteer –
npm install puppeteer
# or "yarn add puppeteer"
When using Puppeteer, include statements that will be looks like below –
puppeteer = require(‘puppeteer’)
Difference between Puppeteer and Puppeteer-core:
Puppeteer-core doesn’t download the Chromium browser automatically during installation.
Puppeteer-core does not consider all PUPPETEER_* env variables.
In most projects, we are using the Puppeteer product package.
Headless Chrome:
Headless chrome means the Puppeteer is interacting with a chrome browser as a background application, which means that the chrome UI is not visible on the screen. By default, Puppeteer launches the application as headless chrome. Code sample to launch Headless Chrome –
In this example, we are opening the headless chrome, i.e., the Chrome UI will not be visible. It can be done by passing the headless flag as true to the Puppeteer.launch method().
Headful chrome means the Puppeteer is interacting with a chrome browser for which chrome UI is visible on the screen. By default, Puppeteer launches the application as headless chrome. Code sample to launch Headful Chrome –
In this example, we are opening the chrome, which is visible to us. It can be done by passing the headless flag as false to the Puppeteer.launch() method.
Puppeteer works with predefined environment variables to support its operations. If Puppeteer doesn’t find the environment variables during the installation, a lowercased variant of these variables will be used from the npm config (manages the NPM Configurations file). The environment variables are not considered by the Puppeteer-core package. The most important Puppeteer environment variables are –
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: It instructs not to download bundled Chromium during the installation step.
PUPPETEER_DOWNLOAD_HOST: It overwrites URL prefix that can be used to download Chromium.
PUPPETEER_DOWNLOAD_PATH: It overwrites the download folder path. Defaults path is – “<root>/.local-chromium/” where <root> is the package root of puppeteer.
HTTP_PROXY, HTTPS_PROXY, NO_PROXY: These variables define the proxy settings to download Chromium during the installation.
PUPPETEER_CHROMIUM_REVISION: It defines a specific version of Chromium to be used by the Puppeteer.
PUPPETEER_EXECUTABLE_PATH: It specifies an executable path to be used in Puppeteer.launch method.
PUPPETEER_PRODUCT: It defines which browser is to be used by Puppeteer. The value has to be either chrome or firefox.
Conclusion:
In this introductory article on Puppeteer Tutorial, we have learned about Puppeteer overview and Puppeteer Environment Variables. In the next article of the Puppeteer tutorial, we will learn about the Puppeteer Web Scraping and Puppeteer Test Automation overview. Please click here to visit the reference portal for this Puppeteer Tutorial. Also, please click here to learn Selenium from LambdaGeeks.
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 :
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 :
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 :
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;
}
}
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.
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 ="{\
" +
" \\"testCaseNumber\\" : \\""+testCaseNumber+"\\",\
" +
" \\"status\\" : \\""+status+"\\",\
" +
" \\"testDescription\\" : \\""+testDesc+"\\",\
" +
" \\"exceptionType\\" : \\""+exceptionType+"\\",\
" +
" \\"detailedError\\":\\""+detailedError+"\\"\
" +
" \
" +
"}";
}
@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 ="{\
" +
" \\"testCaseNumber\\" : \\""+testCaseNumber+"\\",\
" +
" \\"status\\" : \\""+status+"\\",\
" +
" \\"testDescription\\" : \\""+testDesc+"\\",\
" +
" \\"exceptionType\\" : \\""+exceptionType+"\\",\
" +
" \\"detailedError\\":\\""+detailedError+"\\"\
" +
" \
" +
"}";
// 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 ="{\
" +
" \\"testCaseNumber\\" : \\""+testCaseNumber+"\\",\
" +
" \\"status\\" : \\""+status+"\\",\
" +
" \\"testDescription\\" : \\""+testDesc+"\\",\
" +
" \\"exceptionType\\" : \\""+exceptionType+"\\",\
" +
" \\"detailedError\\":\\""+detailedError+"\\"\
" +
" \
" +
"}";
}
@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 .
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 :
selenium design patterns and best practices –hybrid 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 :
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.
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.
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 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.
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.
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 :
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:
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.
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.
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.
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 :
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 :
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 ");
}
}
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();
}
}
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 :
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.
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 :
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 :
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 :
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.
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.
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 :
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.
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.
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) {
\t\ttry {
\t\t\tWebElement element = driver.findElement(locator);
\t\t\tActions actions = new Actions(driver).doubleClick(element);
\t\t\tBASE_LOGGER.info("Performed the double Click on the Element : " + locator);
\t\t} catch (StaleElementReferenceException e) {
\t\t\tBASE_LOGGER.error("Element is not attached to the page document " + e.getCause().getMessage());
\t\t} catch (NoSuchElementException e) {
\t\t\tBASE_LOGGER.error("Element " + locator + " was not found in DOM " + e.getCause().getMessage());
\t\t} catch (Exception e) {
\t\t\tBASE_LOGGER.error("Element " + locator + " was not clickable " + e.getCause().getMessage());
\t\t}
\t}
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.
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.
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.
VBScript Tutorial #10: VBScript Conversion Functions and VBScript Format Functions
VBScript Tutorial #11: VBScript Other Functions
Through out this “VBScript Array Functions” article, we will explains the different types of frequently used vbscript array functions with examples. The important functions related to array are vbscript join, vbscript array, vbscript filter, vbscript split, etc.
VBScript Tutorial #8: VBScript Array Functions
VBScript Array Functions:
While working with arrays in vbscript, we can use in-build vbscript array functions to perform important array-related operations such as create, manipulate, conversion, etc. This article (VBScript Array Functions) contains all the important built-in VBScript array functions, which are mostly used in programs.
VBScript Array Functions – Summary:
vbscript Array – Defines an array based on given data values.
vbscript Filter – Defines a array which is a subset of another one-dimensional string array. The new array is created based on filter criteria.
vbscript IsArray– Test a array variable and return a Boolean value based on the result.
vbscript Join– Converts an array and returns a string value where all the array elements are separated by a specific delimiter.
vbscript Split– Converts a string into a zero-based, one-dimensional array.
vbscript UBound– Returns the upper index of an array that indicates the dimension.
VBScript Array Functions – Details:
All the important vbscript array functions are explained in this section with a proper example.
vbscript Array:
vbscript array function defines an array based on given data values. The array elements are passed the arguments in the vbscript array function.
Syntax: Array(arglist)
Parameter Description:
arglist – These are the mandatory parameters. The list(separated by comma) of arguments are basically the elements of the array.
Example:
In the below example, we will create an array of weekdays using vbscript array function and display the first day of the week (0 index) in a message box.
dayArray = Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
msgbox "The first day of week: " & dayArray(0)
Output (Message Box):
The first day of week: Mon
vbscript Filter:
vbscript filter function defines a zero-based array that contains a subset of a one-dimensional string array. The one-dimensional new array is created based on filter criteria.
string_array – It’s a mandatory parameter which indicates a one-dimensional array of string.
value – It’s a mandatory parameter which represents the filter criteria, i.e. the string expression to search in the array.
include – It’s an optional Boolean parameter. If we provide “true” value as include parameter, it includes the elements which contain the searched criteria. Else, it will exclude the elements which contain the criteria. The default value is true.
compare – This is also an optional parameter which specifies the comparison type as binary or textual. If not specified, by default parameter value will be treated as zero. The possible values are –
· 0 = vbBinaryCompare – Perform a binary checking
· 1 = vbTextCompare – Perform a textual checking
Example:
In the below example, we will create an array using vbscript filter function based on the elements of the weekday array, which contains “S” character.
dayArray = Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
filterArray = Filter(dayArray, "S")
for each e in filterArray
\tmsgbox e
next
Output (Message Box):
Sat
Sun
vbscript IsArray:
vbscript isarray function tests and returns a boolean value after checking a specified variable is an array or not. For a valid array, the return value is true else false will be returned.
Syntax: IsArray(variable)
Parameter Description:
variable – It’s a required parameter which needs to be verified.
Example:
In the below example, we will check a variable if it’s an array or not.
vbscript join function converts an array into a string expression where all the array elements are separated by a specific delimiter.
Syntax: Join(array [, delimiter])
Parameter Description:
array – It’s a required parameter which represents a one-dimensional array.
delimiter – It’s an optional parameter which is used to separate each array element after converting into string expression.
Example:
In the below example, we will convert the weekday array into a string expression using vbscript join function where all the elements will be separated by a comma.
Expression – It’s a required parameter which represents a string expression.
delimiter – It’s an optional parameter which is used to differentiate each array elements within the string expression. The default value is space.
count – It’s an optional parameter which represents the count of substring/array elements to be returned. The default value -1 specifies that entire string will be returned as single element of the array.
compare – This is also an optional parameter which specifies the comparison type as binary or textual. If not specified, by default parameter value will be treated as zero. The possible values are –
· 0 = vbBinaryCompare – Perform a binary checking
· 1 = vbTextCompare – Perform a textual checking
Example:
In the below example, we will convert a string expression, contains all the day name of a week which are separated by semi-column, using vbscript split function. After the conversion, we will display the first and last day of a week.
string_expression = "Mon;Tue;Wed;Thu;Fri;Sat;Sun"
dayArr = Split(string_expression, ";")
msgbox "First day-> " & dayArr(0) & " and Last day-> " & dayArr(6)
Output (Message Box):
First day-> Mon and Lat day-> Sun
vbscript LBound:
vbscript lbound function return the lower index, i.e. smallest subscript of an array for the specified dimension. The lbound value for an array is always 0.
Syntax: Lbound(array[,dimension])
Parameter Description:
array – It’s a required parameter which represents a one-dimensional array.
dimension – It’s an optional parameter which indicates the dimension of the array for which smallest subscript will be returned. The value will be 1 for the first dimension, 2 for the second dimension and so on. The default value is 1.
Example:
In the below example, we will find and display the lower subscript value using vbscript lbound function.
vbscript ubound function return the upper index, i.e. the largest subscript of an array for the specified dimension. The ubound value for an array represent the highest array index i.e. number of element minus one. This function helps to calculate the length of an array.
Syntax: Ubound(array[,dimension])
Parameter Description:
array – It’s a required parameter which represents a one-dimensional array.
dimension – It’s an optional parameter which indicates the dimension of the array for which smallest subscript will be returned. The value will be 1 for the first dimension, 2 for the second dimension and so on. The default value is 1.
Example:
In the below example, we will find and display the longest subscript value using vbscript ubound function.
Through this VBScript Array Functions article, we have learned about the frequently used VBScript Array Functions such as, vbscript array, vbscript filter, vbscript join, vbscript split function, etc. In the next vbscript tutorial, we will explain more functions on VBScript functions. Please click to read more on vbscript from here.
In this VBScript Tutorial, we are going to learn about the most important and frequently used VBScript Date Functions and VBScript Time Functions, including vbscript Cdate, vbscript DateAdd, vbscript date, vbscript time, vbscript FormatDateTime function, etc. All the vbscript date functions and vbscript time functions are explained with examples.
VBScript Tutorial #6:VBScript Date Functions
While working with dates in vbscript, we can use in-build vbscript date functions to perform important date-related operations such as capture system date, date conversion, extract different parts of a date, calculation, formatting, etc. This article(VBScript Date Functions) contains all the important built-in VBScript date functions, which are mostly used in programs.
VBScript Date Functions – Summary:
vbscript Cdate – Convert a valid date and time expression into datatype as the date.
All the important vbscript date functions are explained in this section with a proper example.
vbscript Cdate:
vbscript cdate function used to convert a string expression of a date into date format and returns the converted date value. While updating any date type field such as database field with the date data type, we need to convert the string into date format. Otherwise, an error will be thrown.
Syntax:Cdate(date)
Parameter Description:
date – It denotes any valid date and time expression in string format.
Example:
In the below example, any valid date expression will be converted into date format using vbscript Cdate function.
strDate = "10-Feb-2021"
dtDate = Cdate(strDate)
‘After the date conversion the variable dtDate will hold the value with date format (#10-Feb-2021#).
vbscript Date:
The vbscript date function returns the present system date.
Syntax: Date
Example:
In the below example, we will store the current system date in a variable and display in the message box.
sysDate = Date
msgbox " Current system date is " & sysDate
' OutPut (Msgbox):
' Current system date is 04-Jan-2020
vbscript DateAdd:
vbscript dateadd function returns the calculated date value after adding with specific interval time.
Syntax: DateAdd(interval,number,date)
Parameter Description:
number – It represents any number we want to add. It can be positive(future date) or negative(past date) value.
date – It represents any valid date.
interval – It’s a mandatory parameter which denotes the interval of time. The different interval options are –
· yyyy – Represents the quarter interval.
· q – Represents the quarter interval.
· m – Represents the month interval.
· y – Represents the the day of a year interval.
· d – Represents the day interval.
· w – Represents the weekday interval.
· ww – Represents the week of the year interval.
· h – Represents the hour.
· n – Represents the minute.
· s – Represents the second.
Example:
In the below example, we will calculate the future date after adding two months with the system date using vbscript dateadd function.
sDate = "04-Jan-2021"
newDate = Cdate(sDate)
newDate = DateAdd("m",+2,sDate)
msgbox "Future date after adding 2 months with " & sDate & " is " & newDate
vbscript DateDiff:
vbscript datediff function returns the number of an interval between two dates.
interval – It’s a mandatory parameter which denotes the interval of time. The different interval options are –
· yyyy – Represents the quarter interval.
· q – Represents the quarter interval.
· m – Represents the month interval.
· y – Represents the the day of a year interval.
· d – Represents the day interval.
· w – Represents the weekday interval.
· ww – Represents the week of the year interval.
· h – Represents the hour.
· n – Represents the minute.
· s – Represents the second.
date – It represents any valid date expression.
firstdayofweek – It’s an optional field which denotes the day of the week. The available values are –
0 = vbUseSystemDayOfWeek (API Setting for National Language Support)
1 = vbSunday (Sunday – default)
2 = vbMonday (Monday)
3 = vbTuesday (Tuesday)
4 = vbWednesday (Wednesday)
5 = vbThursday (Thursday)
6 = vbFriday (Friday)
7 = vbSaturday (Saturday)
firstweekofyear – It’s also an optional field which denotes the first week of the year. The available values are –
0 = vbUseSystem (API Setting for National Language Support)
1 = vbFirstJan1 (Start with the week when January 1 occurs – default)
2 = vbFirstFourDays (It represent the start week where minimum 4 days are fall in the new year)
3 = vbFirstFullWeek (It represent the week which completely falls in new year)
Example:
Below example evaluates the month part of a given date using vbscript datepart function.
date=Cdate("04-Jan-2021")
monthPart = DatePart("d", date)
msgbox "The month part - " & monthPart
' OutPut (Msgbox):
' The month part - 1
vbscript IsDate:
vbscript isdate function returns the boolean value as true or false if any string expressing can be converted into date format. Vbscript isdate function is used to test a date expression.
Syntax: Isdate(date)
Parameter Description:
date – It denotes any date expression to be verified.
Example:
In the below example, any given test expression is checked for the valid date expression.
date = "04-Jan-2021"
boolResult = IsDate(date)
msgbox "Is Valid date ? Ans: " & monthPart
' OutPut (Msgbox):
' Is Valid date ? Ans: true
vbscript Day:
vbscript day function extracts the number(1-31) that represents the day from a valid date expression.
Syntax: Day(date)
Parameter Description:
date – It’s a valid date expression.
Example:
In the below example, the day part will be extracted from a given date using vbscript day function.
date = Cdate("04-Jan-2021")
num = Day(date)
msgbox "The day part is - " & num
' OutPut (Msgbox):
' The day part is - 4
vbscript Month:
vbscript month function extracts the number(1-12) that represents the month from a valid date expression.
Syntax: Month(date)
Parameter Description:
date – It’s a valid date expression.
Example:
In the below example, month will be extracted from a given date using vbscript month function.
date = Cdate("04-Jan-2021")
num = Month(date)
msgbox "The month part is - " & num
' OutPut (Msgbox):
' The month part is - 1
vbscript Year:
vbscript year function extracts the four digit number that represents the year from a valid date expression.
Syntax: Year(date)
Parameter Description:
date – It’s a valid date expression.
Example:
In the below example, the year will be extracted from a given date using vbscript year function.
date = Cdate("04-Jan-2021")
num = year(date)
msgbox "The year part is - " & num
' OutPut (Msgbox):
' The year part is - 2021
vbscript MonthName:
vbscript monthname function returns the name of a specific month code(1-12).
Syntax: MonthName(month[,abbreviate])
Parameter Description:
month – It’s representing the code(1-12) for any specific month.
abbreviate – It’s not an mandatory parameter. It represents to check about the name of the month is abbreviated or not. The default value is false.
Example:
month_name = MonthName(12)
msgbox "The month name is - " & month_name
' OutPut (Msgbox):
' The month name is - December
vbscript Weekday:
vbscript weekday function returns the number between 1 and 7 that denotes the day of the particular week.
Syntax: WeekDay(date[,firstdayofweek])
Parameter Description:
date – It’s a valid date expression.
firstdayofweek – It’s an optional field which denotes the start day of the week. The available values are –
0 = vbUseSystemDayOfWeek (API Setting for National Language Support)
1 = vbSunday (Sunday – default)
2 = vbMonday (Monday)
3 = vbTuesday (Tuesday)
4 = vbWednesday (Wednesday)
5 = vbThursday (Thursday)
6 = vbFriday (Friday)
7 = vbSaturday (Saturday)
Example:
In the below example, the day representing the week, will be extracted from a given date using vbscript weekday function.
date = Cdate("06-Jan-2021")
num = Weekday(date,1)
msgbox "The week day is - " & num
' OutPut (Msgbox):
' The week day is - 4
vbscript WeekDayName:
vbscript weekdayname function returns the name of a specific day of a week(1-7).
weekday – It’s representing the day code(1-7) for any week.
abbreviate – It’s not an mandatory parameter. It represents to check about the name of the day is abbreviated or not. The default value is false.
firstdayofweek – It’s an optional field which denotes the start day of the week. The available values are –
0 = vbUseSystemDayOfWeek (API Setting for National Language Support)
1 = vbSunday (Sunday – default)
2 = vbMonday (Monday)
3 = vbTuesday (Tuesday)
4 = vbWednesday (Wednesday)
5 = vbThursday (Thursday)
6 = vbFriday (Friday)
7 = vbSaturday (Saturday)
Example:
day_name = WeekdayName(2)
msgbox "The name of the week day - " & day_name
' OutPut (Msgbox):
' The name of the week day - Monday
VBScript Tutorial #7: VBScript Time Functions
While working with time in vbscript, we can use in-build vbscript time functions to perform important time-related operations such as capture system time, extract different parts of any time, calculation, time formatting, etc. This article(VBScript Time Functions) contains all the important built-in VBScript time functions, which are mostly used in programs.
Important VBScript Time Functions – Summary:
vbscript Hour– Extract the hour of the day as a number(0-23) from date/time expression.
vbscript Minute – Extract the minute of the hour as a number(0-59) from date/time expression.
vbscript Second– Extract the second of the minutes as a number(0-59) from a date/time expression.
We will explain all the essential vbscript time functions in this section with a proper example.
vbscript Hour:
vbscript hour function extracts the hour of the day as a number between 0 to 23 from time expression.
Syntax: Hour(time)
Parameter Description:
time – It’s a mandatory parameter that represents a valid time expression.
Example:
In the below example, an hour of the day will be extracted from a valid time expression using vbscript hour function.
numHour = Hour("14:40:35")
msgbox "The hour for the day is - " & numHour
' OutPut (Msgbox):
' The hour for the day is - 14
vbscript Minute:
vbscript minute function extracts the minute of the hour as a number between 0 to 59 from time expression.
Syntax: Minute(time)
Parameter Description:
time – It’s a mandatory parameter that represents a valid time expression.
Example:
In the below example, the minute of the hour will be extracted from a valid time expression using vbscript minute function.
numMin = Minute("14:40:35")
msgbox "The minute for the hour is - " & numMin
' OutPut (Msgbox):
' The minute for the hour is - 40
vbscript Second:
vbscript second function extracts the second of the minute as a number between 0 to 59 from time expression.
Syntax: Second(time)
Parameter Description:
time – It’s a mandatory parameter that represents a valid time expression.
Example:
In the below example, the second of the minute will be extracted from a valid time expression using vbscript second function.
numSec = Second("14:40:35")
msgbox "The second for the minute is - " & numSec
' OutPut (Msgbox):
' The second for the minute is - 35
vbscript Time:
vbscript time function returns the current system time.
Syntax: Time
Example:
In the below example, we will store the current system time in a variable and display in a message box.
sysTime = Time
msgbox " Current system time is " & sysTime
' OutPut (Msgbox):
' Current system time is 14:40:35
vbscript Now:
vbscript now function returns the current system date with timestamp.
Syntax: Now
Example:
In the below example, we will store the current system date and time in a variable and display in a message box.
sysTimeStamp = Now
msgbox "Current system date with time is " & sysTimeStamp
' OutPut (Msgbox):
' Current system date with time is 07-Jan-2021 14:40:35
vbscript Timer:
vbscript timer function returns the count of seconds from 12:00 AM.
Syntax: Timer
Example:
secondCounter = Timer
msgbox "Number of seconds since 12:00 AM " & secondCounter
' OutPut (Msgbox):
' Number of seconds since 12:00 AM 1067.002
vbscript TimeSerial:
vbscript timeserial method fetch the exact time for a mentioned hour, minute and second.
Syntax: TimeSerial(hour, minute, second)
Parameter Description:
hour – It’s a mandatory numeric parameter, denotes hours.
minute – It’s a mandatory numeric parameter, denotes minutes.
second – It’s a mandatory numeric parameter, denotes seconds.
Example:
In the below example, vbscript timeserial function returns the time for the given hours, minutes and seconds.
time = TimeSerial(15,2,20)
msgbox "Specified time is " & time
' OutPut (Msgbox):
' Specified time is 03:02:20 PM
vbscript FormatDateTime:
vbscript formatdatetime function formats and returns a valid and time expression.
Syntax: FormatDateTime(dateExp, format)
Parameter Description:
dateExp– This is a mandatory parameter. It represents a valid date-time expression.
format – It’s an optional arameter that specifies the date and time format. The available return date and time formats are –
0 = vbGeneralDate – This is the default format value (date format: mm/dd/yyyy and time if specified: hh:mm:ss PM/AM).
1 = vbLongDate (date: weekday, monthname, year)
2 = vbShortDate (date: mm/dd/yyyy)
3 = vbLongTime (time: hh:mm:ss PM/AM)
4 = vbShortTime (Return time: hh:mm)
Example:
In the below example, vbscript timeserial function returns the time for the given hours, minutes and seconds.
d=CDate("06-Jan-2021 13:45")
msgbox "Specified formated date time is " & FormatDateTime(d,1)
' OutPut (Msgbox):
' Specified formated date time is Wednesday, Jan 06, 2021
Conclusion:
Through this VBScript Date and Time Functions article, we have learned about the learn about the most important and frequently used VBScript Date Functions and VBScript Time functions, including vbscript Cdate, vbscript DateAdd, vbscript FormatDateTime function, etc. We hope this tutorial has helped a lot to brush up on your basics of VB Scripting. If you want to learn more about VBScript, please click here.