App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide Keyword Driven Framework for Selenium

Keyword Driven Framework for Selenium

By Neha Vaidya & Pawan Kumar, Community Contributors -

What is Keyword Driven Framework?

The keyword-driven framework is based on keywords that form the basis of the functionality, take in parameters, and throw the relevant output. When the code has to cover a lot of functionality, it might need repetitive writing for some sections. Thus, keywords are written to abstract the complexity of the code.

  • The operations or methods are written separately from the script as keywords.
  • These keywords, placed in an external file (Excel sheet), are called using the code. This enables testers to keep each of the functionalities separate.
  • The steps of each test case are represented using keywords, and each keyword is associated with relevant parameters.
  • Testers can create and modify test cases without dealing with the underlying automation code, making the process more user-friendly.

What is a Keyword Driven Framework in Selenium?

A Keyword Driven Framework has all operations and instructions in an external Excel file. Let’s look at the process flow to understand how it works. Even though the process is simple, a structured approach is followed to perform Keyword Driven Testing in Selenium.

Keyword Driven Testing Framework in Selenium

  1. The automation script will read the instructions or test input data from the Excel sheet
  2. The input data is entered in the application under test
  3. The test cases are performed and results are returned
  4. The test output data is stored in the Excel sheet

What is Keyword Driven Testing?

Keyword-Driven Testing, or Keyword-Driven Testing Framework or simply Keyword Testing is a test automation framework that abstracts the technical details of test implementation and allows testers to create and manage tests using a more user-friendly and business-oriented language.

Tests are represented using a sequence of keywords, where each keyword corresponds to a specific action or operation to be performed on the application under test. These keywords are defined in a library or repository, and testers use them to create test cases by combining keywords in a meaningful sequence.

Why perform Keyword Driven Testing? 

Keyword driven testing addresses common challenges in test automation by providing a structured approach that separates test design from automation implementation. The following are the benefits:

  • It empowers technical and non-technical stakeholders to collaborate effectively, ensures efficient test case maintenance, and enhances the overall quality of the testing process.
  • With Keyword-Driven Testing, modifying or updating tests often involves changing the keyword definitions or parameters rather than rewriting entire test scripts.
  • Test cases can be developed more quickly using predefined keywords, as they encapsulate complex automation logic.
  • High-level keywords make conveying testing progress and results easier for management and other teams.
  • Using standardized keywords promotes consistency in test case design and execution.
  • Test cases can be easily customized by rearranging, adding, or modifying keywords to create new testing scenarios.

Tools Used for Keyword Driven Testing

  • Selenium with TestNG or JUnit: Selenium can be combined with testing frameworks like TestNG or JUnit to create a Keyword-Driven Testing framework. You can define keywords as methods and use annotations or configuration files to map keywords to actual test actions.
  • Robot Framework: Robot Framework is a powerful and user-friendly test automation framework that supports Keyword-Driven and Data-Driven Testing. It has built-in keywords for various actions; you can create custom keywords. It has a simple tabular syntax for test case design and supports various test libraries and extensions.

Advantages And Disadvantages of Keyword Driven Testing Framework

Advantages Disadvantages
Code Reusability Keyword Management
Platform independent Test ScriptsExtensive Planning 
Enhanced Productivity Expertise required to write test scripts
Application abstraction Time taken to write test scripts is higher than usual 

The benefits are evident enough to prove the mettle of Keyword Driven Framework in Selenium. Testers can overcome many challenges while using other framework approaches using Keyword Driven Framework in Selenium.

Components of a Keyword Driven Framework

  1. Excel Sheet – It is used to store the data for test cases, such as keywords
  2. Object Repository – This stores the locator values for web elements
  3. Function Library – It is used to create functions that perform actions
  4. Test Data Sheet – This is an Excel file storing the data values within objects
  5. Test Scripts – These are the scripts to interact with the application under test
  6. Driver Script – This is the driver engine that interacts with all test scripts
  7. Selenium – It is used for environment setup. Other tools can also be used for this purpose

Keyword Driven Framework Using Selenium WebDriver

Frameworks in Selenium help separate the code and the data to help maintain test cases. Frameworks help make the code reusable, readable, and reduce the cost of maintenance. This section will explore a Keyword Driven Testing Framework using Selenium Webdriver.

Let’s create a simple design of a keyword-driven framework with the help of a scenario. The scenario will automate the end-to-end flow of a web application.

Scenarios to be automated:

  1. Open a Browser
  2. Navigate to URL https://bstackdemo.com/
  3. Click the Sign In button
  4. Enter Username
  5. Enter password
  6. Click on the Login button
  7. Validate username on homePage
  8. Click on the Logout button
  9. Close the browser

Prerequisites:

  1. First configure Eclipse with Selenium
  2. Create a Maven project and add dependencies in the pom.xml file below, which contains dependencies related to the Selenium project and excelSheethandling.
<?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.keyword_driven_framework</groupId>

    <artifactId>keyword_driven_framework</artifactId>

    <version>1.0-SNAPSHOT</version>

    <properties>

        <maven.compiler.source>1.8</maven.compiler.source>

        <maven.compiler.target>1.8</maven.compiler.target>

    </properties>

    <dependencies>

        <!-- Other dependencies, if any -->

       

        <!-- Selenium WebDriver -->

        <dependency>

            <groupId>org.seleniumhq.selenium</groupId>

            <artifactId>selenium-java</artifactId>

            <version>4.0.0</version> <!-- Replace with the latest version available -->

        </dependency>

        <dependency>

            <groupId>io.github.bonigarcia</groupId>

            <artifactId>webdrivermanager</artifactId>

            <version>5.3.1</version> <!-- Use the latest version available -->

        </dependency>

        <dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi-ooxml</artifactId>

            <version>3.11</version>

            </dependency>

    </dependencies>

</project>

Step 1: To design a Keyword Driven Framework, first identify all the actions to be performed for automated testing of an application. In the above scenario, seven steps have to be completed.

Step 2: Once all actions are identified, the next step is to create a keyword map table in the Excel sheet. Keyword map table is a table in an Excel sheet that defines all the keywords available for test automation projects.

The table below shows the keyword map table for the above scenarioKeyword Driven Testing Framework

Step 3: Once all keywords have been identified, the next step is to place the Excel sheet in the project package. Create a package named ‘excelData’ by right-clicking on the Project. For this, go to New > Package.

Keyword Driven Framework in Selenium

Place the newly created Excel file in the package directory locally on the computer. The package structure of the keyword-driven framework can be seen in the screenshot below.

Keyword driven framework in selenium webdriver code with example
This structure is highly recommended as it is easy to understand, use, and maintain.

Step 4: Create a new package named “utility”. Now, create a new class file named “Constants” in which the tester will define constants like URL, filePath, and excelData. Source code looks as below:

package com.keyword_driven_framework.utility;

public class Constants {

public static final String URL = "https://bstackdemo.com/";

//Mention the path to your excel file

public static final String filePath = "D:\\DemoFile.xlsx";

public static final String excelData = "DemoFile.xlsx";

public static final String username = "Your_Username";

public static final String password = "Your_password";

}

Step 5: Now, write code for each action keyword. Create a new package named “keywordDriven”. Create a new class file named “Action_Keyword”. In this class, create methods for each Action Keyword identified in Excel.

package com.keyword_driven_framework.keywordDriven;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.firefox.FirefoxOptions;

import com.keyword_driven_framework.utility.Constants;

public class Action_keyword

{

public static WebDriver driver;

public void openBrowser()

{

System.setProperty("webdriver.gecko.driver","path_to_driver");

FirefoxOptions options = new FirefoxOptions();

WebDriver driver = new FirefoxDriver(options);

driver.manage().window().maximize();  

}

public void navigate()

{

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get(Constants.URL);

}

public void clickSignIn_h()

{

driver.findElement(By.xpath("//a[@id='signin']")).click();

}

public void enterEmail()

{

driver.findElement(By.xpath("(//div[@class=' css-1wa3eu0-placeholder'])[1]")).sendKeys(Constants.username);

}

public void enterPassword()

{

driver.findElement(By.xpath("(//div[@class=' css-1wa3eu0-placeholder'])[2]")).sendKeys(Constants.password);

}

public void clickSignIn()

{

driver.findElement(By.xpath("//button[@id='login-btn']")).click();

}

public void verifyUserName()

{

    String username =new String ("your_username");

    username.equals(driver.findElement(By.xpath("//span[@class='username']")));

}

public void logout()

{

driver.findElement(By.xpath("//a[@id='logout']")).click();

}

public void verifySignBtn()

{

     String signIn =new String ("Sign In");

     signIn.equals(driver.findElement(By.xpath("//a[@id='signin']")));

}

public void closeBrowser()

{

driver.quit();

}

}

Step 6: Write code to read data from an Excel sheet in this step. For this, use an Apache POI library, which allows testers to read, create, and edit Microsoft Office documents using Java.

Create a new package named “excelUtility” and then create a new class file named “ReadExcelSheet”. Look at the following source code to read all keywords from the step table.

package com.keyword_driven_framework.excelUtility;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

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

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

import com.keyword_driven_framework.utility.Constants;

public class ReadExcelSheet

{

public ArrayList readExcelData(int colNo) throws IOException

{

String filePath = Constants.filePath;

File file = new File(filePath);

// Create an object of FileInputStream class and pass file as parameter to its constructor.

FileInputStream fis = new FileInputStream(file);

XSSFWorkbook wb = new XSSFWorkbook(fis);

XSSFSheet sheet = wb.getSheet("Sheet1");

Iterator row = sheet.rowIterator();

row.next();

ArrayList<String> a = new ArrayList();

// Checking the next element availability using the reference variable row.

while(row.hasNext())

{

Row r = (Row) row.next();

// Moving cursor to the cell by getting a cell number.

Cell c = r.getCell(colNo);

String data = c.getStringCellValue();

a.add(data);

a.add(((Row) row.next()).getCell(colNo).getStringCellValue());

}

System.out.println("List: " +a);

// Return the data to the Arraylist method.

return a;

}

public void DemoFile(int i) {

// TODO Auto-generated method stub

}

}

Step 7: Next step is to write code for calling readExcelData() method of ReadExcelSheet class and methods of ActionKeywords class. Create a new package named “executionEngine” and write the following source code by creating a class named “ExecutionTest”.

package com.keyword_driven_framework.executionEngine;

import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

import com.keyword_driven_framework.excelUtility.ReadExcelSheet;

import com.keyword_driven_framework.keywordDriven.Action_keyword;

public class ExecutionTest

{

public static void main(String[] args) throws IOException, Exception, IllegalArgumentException, InvocationTargetException

{

ReadExcelSheet rs = new ReadExcelSheet();

rs.DemoFile(4);

Action_keyword k = new Action_keyword();

k.openBrowser();

k.navigate();

k.clickSignIn_h();

k.enterEmail();

k.enterPassword();

k.clickSignIn();

k.verifyUserName();

k.logout();

k.verifySignBtn();

k.closeBrowser();

System.out.println("Test executed successfully");

}

}

Observe the output by executing the code:

A more advanced keyword-driven framework would involve data-driven capabilities, better error handling, and more modular test scenarios and keyword organization.

keyword driven framework in Selenium

Difference Between Data Driven And Keyword Driven Framework

Keyword Driven Framework Data Driven Framework 
Easy to maintain due to more abstraction layers between test scripts, test data, keywords, etc.Comparatively harder to maintain since the abstraction is only between test data and test scripts
Planning has to be extensive and precise for keyword driven frameworksPlanning is easy since it is only needed for test data and test scripts
It is possible to write test scripts even before the product has finished development stageOne has to wait for development to finish before writing test cases

Overall, we can conclude that Keyword-Driven Testing aims to improve the efficiency and effectiveness of software testing by providing a structured, reusable, and maintainable approach to test automation.

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

Data Driven Framework in Selenium

TDD vs BDD vs ATDD : Key Differences

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack