Keyword Driven Framework Example

In this framework, keywords are developed which are equal to a unit level functionality. It is an independent framework which perform automation based on the keywords specified in the excel sheet. Based on the type of application, the number of keywords will be increased to handle different functionalities.

The below are the few keywords which are used commonly in the web applications.

open_Browser(browserName): In this method we need to pass browser name which will invoke the respective driver. example, If the user pass 'chrome' as a browser name, it will invoke the chrome driver.

enter_TextOnTextBox(locator, locatorValue, textToEnter) : This method is used to enter the text by using sendkeys method. Here we need to use three parameters the first one is locator type that can be id / name / any other locator, second parameter should be the locator value And the last method should be the data that you want to pass into the text field.

click_On_Link(locatorType, locatorValue): Here we have to have two parameters, First parameter is locator type, and it should be linkText or partialLinkText and the text that we need to click on.

select_Checkbox(locatorType, locatorValue) and deselect_Checkbox(locatorType, locatorValue) : Here we need to have two parameters locator type and locator value which will select / deselect the checkbox. If we need to select/deselect multiple check boxes we need to handle it in a different way.

After defining the methods, we need a method to read the data (methods and parameters) from excel sheet. And once when the data is ready, we need to invoke that particular method dynamically as we don't know the methods until we start executing hence we need to handle it during Run time.

To make this work we can use the concept of Java 'Reflection API' which commonly used for observing and/or modifying program execution at runtime.

You can find good examples on reflection here
click here for Java Reflection API

Here is the simple keyword driven framework example :

Step 1: We will define a class called KeyWordExample, which will have all the resuable methods, driver invocation, taking the screen shot and reporting mechanism.

package com.keyword.sample;

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

public class KeyWordExample {

	static WebDriver driver;
	static WebDriverWait wait;

	public void open_Browser(String browserName) {
		try {
			if (browserName.equalsIgnoreCase("Firefox")) {
				driver = new FirefoxDriver();
			} else if (browserName.equalsIgnoreCase("chrome")) {
				System.setProperty("webdriver.chrome.driver",
						"D:/Jars/chromedriver.exe");
				driver = new ChromeDriver();
			} else if (browserName.equalsIgnoreCase("IE")) {
				System.setProperty("webdriver.ie.driver",
						"D:/Jars/IEDriverServer.exe");
				driver = new InternetExplorerDriver();
			}
		} catch (WebDriverException e) {
			System.out.println(e.getMessage());
		}
	}

	public void enter_URL(String URL) {
		driver.navigate().to(URL);
	}

	public By locatorValue(String locatorTpye, String value) {
		By by;
		switch (locatorTpye) {
		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 enter_Text(String locatorType, String value, String text) {
		try {
			By locator;
			locator = locatorValue(locatorType, value);
			WebElement element = driver.findElement(locator);
			element.sendKeys(text);
		} catch (NoSuchElementException e) {
			System.err.format("No Element Found to enter text" + e);
		}
	}

	public void click_On_Link(String locatorType, String value) {
		try {
			By locator;
			locator = locatorValue(locatorType, value);
			WebElement element = driver.findElement(locator);
			element.click();
		} catch (NoSuchElementException e) {
			System.err.format("No Element Found to enter text" + e);
		}
	}

	public void click_On_Button(String locatorType, String value) {
		try {
			By locator;
			locator = locatorValue(locatorType, value);
			WebElement element = driver.findElement(locator);
			element.click();
		} catch (NoSuchElementException e) {
			System.err.format("No Element Found to perform click" + e);
		}
	}
	
	public void close_Browser() {
		driver.quit();
	}
}

Step 2: We will define other class called KeyWordExecution, which takes the responsibility of retrieving the data from excel sheet, identify the locators and parameters and invoke the respective methods in the 'KeyWordExample' class.

package com.keyword.sample;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class KeyWordExecution {

	public void runReflectionMethod(String strClassName, String strMethodName,
			Object... inputArgs) {

		Class<?> params[] = new Class[inputArgs.length];

		for (int i = 0; i < inputArgs.length; i++) {
			if (inputArgs[i] instanceof String) {
				params[i] = String.class;
			}
		}
		try {
			Class<?> cls = Class.forName(strClassName);
			Object _instance = cls.newInstance();
			Method myMethod = cls.getDeclaredMethod(strMethodName, params);
			myMethod.invoke(_instance, inputArgs);

		} catch (ClassNotFoundException e) {
			System.err.format(strClassName + ":- Class not found%n");
		} catch (IllegalArgumentException e) {
			System.err
					.format("Method invoked with wrong number of arguments%n");
		} catch (NoSuchMethodException e) {
			System.err.format("In Class " + strClassName + "::" + strMethodName
					+ ":- method does not exists%n");
		} catch (InvocationTargetException e) {
			System.err.format("Exception thrown by an invoked method%n");
		} catch (IllegalAccessException e) {
			System.err
					.format("Can not access a member of class with modifiers private%n");
			e.printStackTrace();
		} catch (InstantiationException e) {
			System.err
					.format("Object cannot be instantiated for the specified class using the newInstance method%n");
		}
	}

	public static void main(String[] args) {
		KeyWordExecution exeKey = new KeyWordExecution();
		ReadExcel excelSheet = new ReadExcel();
		excelSheet.openSheet("D:/testCaseSheet.xls");
		for (int row = 1; row < excelSheet.getRowCount(); row++) {
			List<Object> myParamList = new ArrayList<Object>();
			String methodName = excelSheet.getValueFromCell(0, row);
			for (int col = 1; col < excelSheet.getColumnCount(); col++) {
				if (!excelSheet.getValueFromCell(col, row).isEmpty()
						& !excelSheet.getValueFromCell(col, row).equals("null")) {
					myParamList.add(excelSheet.getValueFromCell(col, row));
				}
			}

			Object[] paramListObject = new String[myParamList.size()];
			paramListObject = myParamList.toArray(paramListObject);

			exeKey.runReflectionMethod("com.keyword.sample.KeyWordExample",
					methodName, paramListObject);
		}
	}
}

Step 3: We will create an other class to read the excel sheet. We have used jxl library to read the data from excel. You can also use 'Apache POI' to do the same.

Click here for jxl tutorials

package com.keyword.sample;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {

	Workbook wbWorkbook;
	Sheet shSheet;

	public void openSheet(String filePath) {
		FileInputStream fs;
		try {
			fs = new FileInputStream(filePath);
			wbWorkbook = Workbook.getWorkbook(fs);
			shSheet = wbWorkbook.getSheet(0);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getValueFromCell(int iColNumber, int iRowNumber) {
		return shSheet.getCell(iColNumber, iRowNumber).getContents();
	}

	public int getRowCount() {
		return shSheet.getRows();
	}

	public int getColumnCount() {
		return shSheet.getColumns();
	}
}

The below is the excel file which has provided with four columns :
Project Structure

The main advantage going for keyword driven framework is 'Re-usability', we can re-use the same methods for number of test cases. We can extend the framework by increasing flexibility with minimum effort.

Hope this helps you in understanding about keyword driven framework.

Selenium Tutorials: 

Comments

Hi, Thanks for article very helpful.
I have a question. Can you help me on how to write a keyword driven code for validating the various fields on a webpage.
I have salesforce webpage, which has all the possible types of fields on the page. ex: Text, Dropdown, radio button, checkbox, lookup, datelookup, multi-select checkbox.,etc.
Is there a way where I can write generic methods to validate the different fields on a page.?
Thanks,
Alok

can anyone help me in keyword driven automation framework with Hybrid framework...
if i want to click 15 links from the same page(using xpath) as a loop in keyword and Hybrid framework,
How to loop the xpath in excel sheet
Scenarios follows as,
Open a Browser
Navigate to URL
Click on Department links (15 department links)
Get the title of the page after each click
Navigate back after fetching the title
Close the Browser

In the Excel, next to "Test data" column, can we add a "Test Result" column & update it to pass/fail once every row is executed? Can any one provide the code for doing so?

Also can we add a Test Scenarios Excel like below:-
Test_Scenario_ID Test_Scenario_Excel Execute Execution_Result
1 testCaseSheet Y Pass
2 Application_Hub_View_Timesheet N
3 Application_Hub_Add_Timesheet N

Where in we should be able to list all TS & control which TS to exec & finally update result in Execution result column once TS exec is done?

Hi,

I'm using java reflection to execute my test scripts. Since I have a regression class which is having reflection concept. I have only one @test method in regression class file which is mapped in testNG.xml. Basically the testNG>xml contains only one class where the class will run all other class files. I had a problem to implement parallel execution for this implementation. I have a list of string values(class name) which is going to be used in Class.forName("class name").newInstance(); the class name is getting from list<String> in side of reflection. My requirement is how can I implement multi thread which is going to pick different package at a time. Like I have three threads which has top pick three different class file and execute. next iteration the same three thread has to pick other three class file and execute. Is it possible? pls give me your valuable suggestions.

Could one please provide me the Selenium key word driven framework. It is urgenet pls give me asap.

I am getting the below error by executing this code.Can anyone help me please

"In Class com.keyword.sample.KeyWordExample:::- method does not exists"

" Exception thrown by an invoked method " i am having this error, while running this code.

In Library i wanna use only keyward like click(Page.object) ,type(page.object,"param") etc. how to make it can any one suggest?i m able to create class.click(page.object) but i do not to use class , directly method , how can i ?

How to implement the same using code in Testng framework.

Hi,

Can i use this same code for testNG and HOW?
Please suggest me as soon as possible.
Thanks in advance.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.