Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).

This is an small and simple example of Key Driven Framework to execute test cases using excel sheet in Selenium(JAVA).

         Key Driven framework is based on keywords which are used to control the execution of the script without modifying the actual code. A tester has to just set the keywords which he/she wants to execute during a review cycle. He/she doesn’t need to know anything about the code. In this example, we used Test Case level keywords or we can say high-level keywords. In later stages, we will share a low-level key driven framework example in which user case create his/her own test steps without modifying the selenium code. Nowadays, a hybrid framework is used which is a combination of Keyword Driven and Data Driven Framework.

KeyDrivenExcelStructure
                                                                        KeyDrivenExcelStructure

This Example will include following steps to complete the entire process:

  1. Creating excel sheet with few test cases as in this example we have an excel workbook named “TestCases.xlsx”. Currently, we have following Test Cases:
S.No. Test Case Keyword Description UserPreference Test Data (Expected Result)
1 launchBrowser This test case is mandatory. YES http://www.allinoneblogs.com/
2 homePageWindowTitle Verification of title of the home page. YES All in One Blogs
3 homePageHeading Verification of heading of the Home page. YES Our Vision
4 askAQuestionWindowTitle Verification of window title of the Ask A Question Page. YES Ask A Question – All in One Blogs
5 verifyMailID Verification of E-mail ID in Ask A Question Page. YES allinoneblogs.ashok@gmail.com
6 verifyPhone Verification of Phone No. in Ask A Question Page. NO 991024563

2. In above example we have following columns:

S.No. Contains sequence number of test cases.
Test Case Keyword This column contains the keywords which will be used in our script during automation.
Description Description of test cases defined in above field.
UserPreference Set the user requirement that user wants to execute the individual test case or not.
Test Data (Expected Result) This column will contain the test data to complete the test case.

   3. Create different test cases to test the functionality of various test cases defined in above example. Structure of Project is mentioned below:

KeyDrivenProjectStructure
                                                                   KeyDrivenProjectStructure

4. Now, we have to first read the data from the “TestCases.xlsx” file row by row.
5. Depending on the “UserPreference” column, call a particular method from different classes. While executing this methods script will use “TestData” as arguments or inputs.
6. Once execution gets completed, create a “TestCases_Result.xlsx” sheet with Pass/Fail/Skip status and “Actual Result” columns depending on the “UserPreference”.
7. Currently, we targeted following scenarios:

  1. PASS: Test Case executed successfully and Actual Result mapped with Test Data(Expected Result).
  2. FAIL: Test Case doesn’t meet all test data(expected result) due to any reason.
  3. SKIP: If user set value of ‘User Preference’ other than ‘YES/yes’ or keyword not defined in the script.

 

 

S.No. Test Case Keyword Description UserPreference Test Data (Expected Result) Actual Result Status
1 launchBrowser This test case is… YES http://www.allinoneblogs.com/ Browser launched successfully. PASS
2 homePageWindowTitle Verification of title of… YES All in One Blogs All in One Blogs – Continuous Improvement Is Better … FAIL
3 homePageHeading Verification of heading… YES Our Vision Keyword Not Found. SKIP
4 askAQuestionWindowTitle Verification of window… YES Ask A Question – All in One Blogs Ask A Question – All in One Blogs FAIL
5 verifyMailID Verification of E-mail… YES allinoneblogs.ashok@gmail.com allinoneblogs.ashok@gmail.com PASS
6 verifyPhone Verification of Phone… NO 991024563 NA SKIP

UserDefinedTC.java

import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import testCases.AskAQuestion_TC;

public class UserDefinedTC {

	public static int KEYWORD_INDEX=1;
	public static int USERPREF_INDEX=3;
	public static int TESTDATA_INDEX=4;
	public static int ACTUALDATA_INDEX=5;
	public static int TESTRESULT_INDEX=6;
	public static WebDriver driver;
	
	public static void main(String[] args) throws IOException 
	{
		// Locate Input file to get Test Cases.
		String inputFilePath="userInput\\TestCases.xlsx";
		
		// Locate path to generate Output file with Result.
		String resultFilePath="Result\\TestCases_Result.xlsx";
		String actualResult;
		String testResult="PASS";
		boolean keywordFlag;
		String getUserPref;
		
		ExcelHandling.getExcelFile(inputFilePath);
		ExcelHandling.getSheet("TestCases");
		int TotalRows=ExcelHandling.getRowCount();
		
		// Create TestCases_Result.xlsx File.
		ExcelHandling.createExcelFile(resultFilePath);
		
		// Copy content from input file to Output file.
		ExcelHandling.copyContentToResultSheet();
		
                // Reading data row by row and calling the applicable methods according to the 'userPreference' column.
		for(int currentRow=0;currentRow<=TotalRows;currentRow++)
		{
			keywordFlag=false;
			actualResult="NA";
			getUserPref= ExcelHandling.getDataByRowCol(currentRow,USERPREF_INDEX);
			if(currentRow==0)
			{
				// Add "Actual Result" and "Status" columns in the Result sheet.
				ExcelHandling.updateResult(currentRow,"Actual Result","Status");
				continue;
			}
			if(getUserPref.equalsIgnoreCase("yes"))
			{
				
				String currentKeyword=ExcelHandling.getDataByRowCol(currentRow,KEYWORD_INDEX);
				String testData=ExcelHandling.getDataByKeyword(currentKeyword, TESTDATA_INDEX);
				System.out.println("Current Keyword "+currentKeyword);
				try
				{
					switch(currentKeyword)
					{
						case "launchBrowser":
						{
							keywordFlag=true;
							launchBrowser(testData);
							actualResult="Browser launched successfully.";
							
						}
						break;
						case "homePageWindowTitle":
						{
							keywordFlag=true;
							actualResult=getPageTitle();
							if(actualResult.contentEquals(testData))
								testResult="PASS";
							else
								testResult="FAIL";
						}
						break;
						case "askAQuestionWindowTitle":
						{
							keywordFlag=true;
							AskAQuestion_TC.openAskAQuestionPage();
							actualResult=AskAQuestion_TC.getWindowTitle();
							if(actualResult.contentEquals(testData))
								testResult="PASS";
							else
								testResult="FAIL";
						}
						break;
						case "verifyMailID":
						{
							keywordFlag=true;
						   actualResult=AskAQuestion_TC.getMailID();
						   if(actualResult.contentEquals(testData))
								testResult="PASS";
							else
								testResult="FAIL";
						}
						break;
						case "verifyPhone":
						{
							keywordFlag=true;
							actualResult=AskAQuestion_TC.getPhone();
							   if(actualResult.contentEquals(testData))
									testResult="PASS";
								else
									testResult="FAIL";
						}
						break;
					}
				}
				catch(Exception e)
				{
					actualResult=e.toString();
					testResult="FAIL";
				}
			}
			else
			{
				
				testResult="SKIP";
			}
			
			if(!keywordFlag && getUserPref.equalsIgnoreCase("yes"))
			{
				actualResult="Keyword Not Found.";
				testResult="SKIP";
			}
			
			// Update individual test case with Actual Result and Test Result.
			ExcelHandling.updateResult(currentRow, actualResult, testResult);
		}

		// Write all data to TestCases_Result.xlsx file.
		ExcelHandling.writeData();
		
	}
	
	
	
	public static void launchBrowser(String targetURL)
	{
		System.setProperty("webdriver.chrome.driver", "EXE\\chromedriver.exe");
		driver=new ChromeDriver();
		driver.get(targetURL);
		driver.manage().window().maximize();
	}
	
	public static String getPageTitle()
	{
		String pageTitle=driver.getTitle();
		return pageTitle;
	}

}

ExcelHandling.java

package testCaseExecution;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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;

public class ExcelHandling 
{
	public static File userInputFile;
	public static FileInputStream fis;
	public static XSSFWorkbook workbook;
	public static XSSFSheet sheet;
	
	public static File resultFile;
	public static FileOutputStream fos;
	public static XSSFWorkbook resultWorkbook;
	public static XSSFSheet resultSheet;
	
	
	public static void getExcelFile(String filePath) throws IOException
	{
		userInputFile=new File(filePath);
		fis=new FileInputStream(userInputFile);
		workbook=new XSSFWorkbook(fis);
	}
	
	public static void getSheet(String sheetName)
	{
		sheet=workbook.getSheet(sheetName);
	}
	
	public static int getRowCount()
	{
		int totalRows=sheet.getLastRowNum();
		return totalRows;
	}
	
	public static String getDataByRowCol(int rowIndex,int colIndex)
	{
		String currentData = sheet.getRow(rowIndex).getCell(colIndex).toString();
		return currentData;
	}
	
	public static String getDataByKeyword(String keyword, int valueIndex)
	{
		Iterator rows=sheet.rowIterator();
		String currentData=null;
		while(rows.hasNext())
		{			
			Iterator cells=rows.next().cellIterator();
			while(cells.hasNext())
			{
				Cell currentCell=cells.next();
				String currentCellData=currentCell.toString();
				if(currentCellData.contains(keyword))
				{
					int currentRow=currentCell.getRowIndex();
					currentData= sheet.getRow(currentRow).getCell(valueIndex).toString();
					break;
				}
			}
		}
		return currentData;
	}
	
	public static void createExcelFile(String filePath) throws FileNotFoundException
	{
		resultFile=new File(filePath);
		fos=new FileOutputStream(resultFile);
		resultWorkbook=new XSSFWorkbook();
		
	}
	
	public static void copyContentToResultSheet()
	{
		int inputSheetCount=workbook.getNumberOfSheets();
		for(int i=0;i<inputSheetCount;i++) { XSSFSheet inputSheet=workbook.getSheetAt(i); String inputSheetName=workbook.getSheetName(i); XSSFSheet outputSheet=resultWorkbook.createSheet(inputSheetName); // Create and call method to copy the sheet and content in new workbook. copySheet(inputSheet,outputSheet); } } public static void copySheet(XSSFSheet inputSheet,XSSFSheet outputSheet) { int rowCount=inputSheet.getLastRowNum(); int currentRowIndex=0; if(rowCount>0)
		{
			Iterator rowIterator=inputSheet.iterator();
			while(rowIterator.hasNext())
			{
				int currentCellIndex=0;
				Iterator cellIterator=rowIterator.next().cellIterator();
				while(cellIterator.hasNext())
				{
					String cellData=cellIterator.next().toString();
					if(currentCellIndex==0)
						outputSheet.createRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
					else
						outputSheet.getRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
					
					currentCellIndex++;
				}
				currentRowIndex++;
			}
		}
		
	}
	
	public static void updateResult(int rowIndex,String actualResult,String testResult)
	{
		resultSheet=resultWorkbook.getSheetAt(0);
		resultSheet.getRow(rowIndex).createCell(UserDefinedTC.ACTUALDATA_INDEX).setCellValue(actualResult);
		resultSheet.getRow(rowIndex).createCell(UserDefinedTC.TESTRESULT_INDEX).setCellValue(testResult);
	}
	
	public static void writeData() throws IOException
	{
		
		resultWorkbook.write(fos);
		fos.close();
		System.out.println("Data has been written on result file.");
	}

}

AskAQuestion_TC.java

package testCases;

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import testCaseExecution.UserDefinedTC;

public class AskAQuestion_TC 
{
	static By menuXpath=By.xpath("//a[contains(@href,'ask-a-question')]");
	static By titleXpath=By.xpath("//*[@class='page-title']");
	static By emailXpath=By.xpath("//a[contains(@href,'mailto')]");
	static By phoneXpath=By.xpath("//*[contains(@class,'widget-contact')]/ul/li[2]/div");
	
	public static boolean openAskAQuestionPage()
	{
		// Click on 'Ask A Question' menu option.
		UserDefinedTC.driver.findElement(menuXpath).click();
		
		try
		{
			// Wait until page get load
		WebDriverWait wait= new WebDriverWait(UserDefinedTC.driver, 10);
		wait.until(ExpectedConditions.visibilityOfElementLocated(titleXpath));
		return (true);
		}
		catch(Exception e)
		{
		return(false);
		}
	}
	
	public static String getWindowTitle()
	{
	  return UserDefinedTC.driver.getTitle();
	}
	
	public static String getMailID()
	{
		return UserDefinedTC.driver.findElement(emailXpath).getText(); 
	}
	
	public static String getPhone()
	{
		return UserDefinedTC.driver.findElement(phoneXpath).getText(); 
	}
	
	

}

2128total visits,6visits today

2 thoughts on “Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).”

    1. Hi Khalid,

      In general, a data-driven framework is used to run the same script for a huge amount of test data from any source like properties files, excel files etc. A tester can’t control the execution of the script.
      On the other hand, a Key Driven framework is based on keywords which are used to control the execution of the script without modifying the actual code. A tester has to just set the keywords which he/she wants to execute during a review cycle.

      Nowadays, the hybrid framework is used which is the combination of Keyword Driven and Data Driven Framework.

      Please visit DataProvider Annotation using Excel in Data Driven Framewok. to learn example for the same.

      Hope, this would be helpful for you.

      Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *