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

The framework looks too easy to implement. And its explaining all the doubts, who wanna start switched from QTP to Selenium.

Thanks

I got this to work after a few hours of tweaking my own way to my setup. The only notable change I'd recommend is adding a close of the excel file, otherwise everytime it stops it still has the excel file open and you have to exit (in my case exit Eclipse) entirely to release it.

Steps to Reached :
in Step 1:
instead of calling IE driver , you are calling Chrome driver in try block else if case ...

This tutorial seems to be very helpful for me..!!

Thanks a ton..awesome.

How can we write the status of executable cases in excel using jxl in keydriven framework?

Can you provide a few ideas to implement assertions?

How to run above code without TestNG

You need to execute 'KeyWordExecution' class which has main method and it will run your tests.

Tq U

Add new comment