Selenium

Selenium Keyword Driven Framework Tutorial

This article is a tutorial about the Selenium Keyword Driven Framework. We will see how Keyword Driven Framework speeds up the automated testing process.
 
 
 
 
 
 
 
 
 
 

 

1. Introduction

A keyword-driven framework is a table-driven testing or action word based testing. This is used to speed up automated testing by utilizing the keywords for a common set of actions.

A keyword-driven testing is a scripting technique that uses data files to contain the keywords related to the application being tested. The keywords describe the actions to be performed for each step. Each input must consist of keywords and its needed arguments to execute the test successfully.

In Keyword-Driven Testing, you first identify a set of keywords and then associate an action related to these keywords. Here, every testing action like opening or closing of the browser, mouse click, keystrokes, etc. is described by a keyword such as open_browser, click, Type_text and so on.

2. Technologies Used

  • IntelliJ Idea (Any Java IDE would work)
  • Java 1.8.101 (1.8.x will do fine)
  • GeckoDriver (firefox)
  • ChromeDriver (Chrome)
  • Maven
    • Selenium

3. Keyword Driven Framework

In this section, We will set up a Keyword driven framework written in Java which will read a CSV file of keywords and perform the required actions as described in the CSV file. The Subsections will cover the required components needed for the Keyword Driven Framework to work.

3.1 Drivers

The first step is to download the suitable Web drivers or browser drivers to work. We will cover two drivers – one for firefox and another for chrome.

To download the gecko driver for firefox, Navigate to the Github page and download the appropriate driver for your Operating System as listed in below screenshot.

Selenium Keyword Driven Framework - Gecko Driver Download
Gecko Driver Download

 

After download, unzip the geckodriver in the appropriate place and make a note of the location. As listed in the screenshot, ensure your operating System has Firefox 57 and above.

To download the chrome driver, navigate to the chrome driver google page. Follow a similar process for the chromedriver and note the location of the driver. Alternatively, for macOs users, it can be installed via the command brew install chromedriver which will be installed in /usr/local/bin folder

3.2 Files

There are two important files for setting up the keyword driven framework. First is the property file for the program to work, which we will take a look below

Configuration File

chrome.path=/usr/local/bin/chromedriver
gecko.path=~/geckodriver

These are the locations where the chromedriver and geckodriver are downloaded. These should be valid paths in your system.

Now we will look at the actual keywords file which will be used as input for executing the keyword driven framework.For simplicity, I have used CSV file.In production Systems, it is recommended to use excel file so that it can be easily edited and color coded

Keywords file

Test Case,Locator Type,Locator Value,Args....
open_browser,chrome
open_url,,,http://www.google.com
enter_text,css,input[id=lst-ib],hi
click_at,css,input[value='Google Search']
verify_value,css,input[id=lst-ib],value,hi
click_at,id,logo,
close_browser

The file contains four important parts

  • Test Case/Command – The Keyword indicating the type of action to be performed on the page.
  • Locator Type – Selenium Supports various locator types such as id,CSS,xpath,name,linktext and partiallinktext.
  • Locator Value-Actual value by which the element will be located. For example, to select a textbox, locator type will be CSS and locator value.
  • Args – These actually span multiple columns. These depend on the actual command and used for an extensible purpose. Its use will be explained in the execution section. Comparing with Selenium ide, this is the value to be checked for (or) the value to be inserted into the text box.

3.3 Classes

We will first look at the maven dependency file and then look at the KeywordService Class which is used to leverage the Selenium Webdriver.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.jcg</groupId>
<artifactId>keyworddriven</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.13.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

</project>
  • In lines 7-9, we are creating an artifact named keyworddriven under group com.jcg with version 1.0-SNAPSHOT
  • We are declaring Selenium as a dependency in line 13.
  • We specify Java compiler version as 1.8 in line 26.

Next, we will look at the KeywordService class.

KeywordService.java

package com.jcg.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

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

public class KeywordService {

    WebDriver driver;
    WebDriverWait wait;
    Properties properties;


    public KeywordService() {
        properties = new Properties();
        try {
            properties.load(KeywordService.class.getClassLoader()
                    .getResourceAsStream("application.properties"));
        } catch (IOException e) {
            System.out.println("Properties not loaded");
            e.printStackTrace();
        }
    }

    public void openBrowser(String browserName) {
        if (browserName.equalsIgnoreCase("Firefox")) {
            System.setProperty("webdriver.gecko.driver", properties.getProperty("gecko.path"));
            driver = new FirefoxDriver();
        } else if (browserName.equalsIgnoreCase("chrome")) {
            System.setProperty("webdriver.chrome.driver", properties.getProperty("chrome.path"));
            driver = new ChromeDriver();
        }
//            else if (browserName.equalsIgnoreCase("IE")) {
//                driver = new InternetExplorerDriver();
//            }
    }

    public void openUrl(String url) {
        driver.navigate().to(url);
    }

    private By locatorValue(String locatorType, String value) {
        By by;
        switch (locatorType) {
            case "id":
                by = By.id(value);
                break;
            case "name":
                by = By.name(value);
                break;
            case "xpath":
                by = By.xpath(value);
                break;
            case "css":
                by = By.cssSelector(value);
                break;
            case "linkText":
                by = By.linkText(value);
                break;
            case "partialLinkText":
                by = By.partialLinkText(value);
                break;
            default:
                by = null;
                break;
        }
        return by;
    }

    public void enterText(String locatorType, String value, String text) {
            By locator = locatorValue(locatorType, value);
            WebElement element = driver.findElement(locator);
            element.sendKeys(text);
    }


    public void clickOnLocator(String locatorType, String value) {
        By locator = locatorValue(locatorType, value);
        WebElement element = driver.findElement(locator);
        element.click();
    }

    public void closeBrowser() {
         wait = new WebDriverWait(driver,2);
         driver.close();
    }


    public boolean verify(String locatorType, String value,String attribute,String valueToCheck){
        By locator = locatorValue(locatorType, value);
        WebElement element = driver.findElement(locator);
        String elementValue =element.getAttribute(attribute);
        if(valueToCheck != null){
            return valueToCheck.equalsIgnoreCase(elementValue);
        }
        return element != null;
    }
}

This is the main service code used to execute the action for each of the keywords. There will be a separate class containing the keywords and another one for mapping the keywords to the service.

This class three following properties

  • WebDriver – actual webDriver implementation indicating the type of browser to run the page
  • WebDriverWait – not necessary but used when the browser has to wait for some time before taking action on the page. Until method is used to wait for an element visibility or determine if an element becomes clickable.
  • Properties – This is used to load the property file which contains the location to the drivers.

At first, the constructor runs and loads all the driver properties into the properties object for further use in the methods. This loads the file information in the Properties object. openBrowser is used to open the browser based on user request. In this example, we have catered to Firefox and selenium by providing the driver path. IE has been commented and it follows a similar configuration. This is the starting point of selecting the appropriate Selenium WebDriver for rest of the application. This fires up the appropriate browser in the environment.

openUrl uses the webdriver to open the url specified in the browser. private method locator plays a pivotal role for the rest of the functionality. It allows selecting any element of the page via Selenium exposed mechanisms. Following are the ways in which Selenium can locate an element

  • CSS – Example: input[class=’cls’] -> Selects input tag which has a class cls.
  • Xpath – Example: \\input -> Selects input tag
  • id – selects an element whose id is specified in the code.
  • name – selects an element whose name is specified in the code.
  • linktext – used to select an element which has a link to other pages. Example: <a href=”#”>Click Here</a>. Here, We have to provide Click Here as Link Text to select the element.
  • partiallinktext – Considering the previous example, partiallinktext of Click will select the same element.

All the subsequent methods use the locator method to locate the element. First, is the enterText method. This locates a textbox and fills the textbox with the text provided. clickOnLocator is used to identify a clickable element like link or button and perform the click action on it. verify method is used for the purposes of assertion here. It has two levels of assertion

  • If Webdriver is not able to locate an element, it fails.
  • If a value is provided, we check if the value matches with the value of the specified attribute of the element.

Finally, closeBrowser is used to close the browser. We use WebDriverWait to wait for 2 seconds before closing the browser. WebDriverWait is useful in cases where an action is to be performed after a time delay. Here it is leveraged only to demonstrate its capability.

Main Driver Class

package com.jcg.selenium;

import java.io.BufferedReader;
import java.io.FileReader;

public class KeywordExecutor {
    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
            KeywordService keywordService = new KeywordService();
            String newLine = br.readLine();
            while ((newLine = br.readLine()) != null) {
                System.out.println("Executing command:"+newLine);
                String[] commandLine = newLine.split(",");
                String command = commandLine[0];
                switch (command.toUpperCase()) {
                    case Keywords.OPEN_BROWSER:
                        String browserName = commandLine[1];
                        keywordService.openBrowser(browserName);
                        break;
                    case Keywords.OPEN_URL:
                        keywordService.openUrl(commandLine[3]);
                        break;
                    case Keywords.ENTER_TEXT:
                        keywordService.enterText(commandLine[1],commandLine[2],commandLine[3]);
                        break;
                    case Keywords.CLICK_AT:
                        keywordService.clickOnLocator(commandLine[1],commandLine[2]);
                        break;
                    case Keywords.CLOSE_BROWSER:
                        keywordService.closeBrowser();
                        break;
                    case Keywords.VERIFY_VALUE:
                        boolean success =keywordService.verify(commandLine[1],commandLine[2],commandLine[3],commandLine[4]);
                        if(!success){
                            throw new Exception("Verify failed for["+command+"]");
                        }
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }


    }
}

This is a simple driver program to read the keywords file and execute the appropriate action. We use a Buffered Reader and read the file line by line. We Split the line by comma to separate the keywords. The first word should always be the command which is used to lookup the action to be performed via switch case. Based on the command, the rest of the arguments would differ.

  • openBrowser just needs the browser name whereas openurl needs the url.
  • enterText needs the textbox id and locator type as CSS along with the value to be entered in the textbox.
  • clickAt just needs the locator type and corresponding value.
  • verifyValue needs all the arguments to verify if found value matches with the entered value.

3.4 Execution Results

In this section, We will take a look at the execution results.

  • openbrowser,chrome – This opens up the chrome browser
  • open_url,,,http://www.google.com – This opens the url google.com in the browser.
  • enter_text,css,input[id=lst-ib],hi – This enters the hi in google search textbox. The below screenshot shows the text entered and waiting for google search.
  • click_at,css,input[value=’Google Search’] – This clicks the google search button
  • verify_value,css,input[id=lst-ib],value,hi- This checks if the text entered is hi in the google search results page.
  • click_at,id,logo,- This clicks the google logo in the search results page.
  • close_browser- This closes the browser.

Selenium Keyword Driven Framework - Google Search page
Search Page Highlighted Text and Search Button

 

Selenium Keyword Driven Framework - Search Details
Details with Logo and Text Box Highlighted

 

4. Summary

In this article, We saw a simple keyword file which can be leveraged to search and retrieve results in google. The locator provided can be extended for all sorts of operations. Complex operations can be acheived with this few set of keywords. It can completely automate a lot of manual activities with these few keywords. Verify command can be used for all sort of assertions in software testing.

5. Download the Source Code

Download
You can download the full source code of this example here: keyword driven framework

Rajagopal ParthaSarathi

Rajagopal works in software industry solving enterprise-scale problems for customers across geographies specializing in distributed platforms. He holds a masters in computer science with focus on cloud computing from Illinois Institute of Technology. His current interests include data science and distributed computing.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
anon
anon
5 years ago

why maven? at 2018

Back to top button