Table of Contents

In Previous Chapter we have seen that to perform any Action, we need to compare the value taken from Excel sheet with the value of each method in Action Keyword class. Till the time there are just a few methods, this technique would work fine. But think of a scenario where a new action is adding almost daily in framework. It will be a tedious task to first add a new method in 'ActionKeyword' class then add that method in to compare the statement of 'DriverEngine' test. Think of the size of the list of IF/ELSE loop after a few releases.

Use of Java Reflection Class

Java gives the ability to overcome this problem with the help of Refection Classes. Reflection is a very useful approach to deal with the Java class at runtime as it can be used to load the Java class, call its methods or analysis the class at runtime. If in case you are not familiar with Java much, I would suggest you to simply copy-paste the code and start using it. Else it is better to Google 'Java Reflection Classes' and read about it. Just keep in mind the actual need of it, that we are using it to create a class at runtime and to analyze the Action Keyword class at runtime.

Let me again tell you the need for it in other words, so that the reason can be understood. As of now in the framework, whenever there is an addition of any new method in Action Keyword class, it is required to put that newly created method in the if/else loop of the main Driver Script. Just to avoid that situation it is required to use Java Reflection class, so that when a new method is added, this reflection class will load all the methods of Action Keyword class at run time.

Action Keyword Class:

package config;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ActionKeywords {
		public static WebDriver driver;
	public void openBrowser(){		
		driver=new FirefoxDriver();
		}

	public static void navigate(){	
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		driver.get("https://www.store.demoqa.com");
		}

	public static void click_MyAccount(){
		driver.findElement(By.xpath(".//*[@id='account']/a")).click();
		}

	public static void input_Username(){
		driver.findElement(By.id("log")).sendKeys("testuser_3"); 
		}

	public static void input_Password(){
		driver.findElement(By.id("pwd")).sendKeys("Test@123");
		}

	public static void click_Login(){
		driver.findElement(By.id("login")).click();
		}

	public static void waitFor() throws Exception{
		Thread.sleep(5000);
		}

	public static void click_Logout(){
			driver.findElement (By.xpath(".//*[@id='account_logout']/a")).click();
		}

	public static void closeBrowser(){
			driver.quit();
		}

	}

Note: There is no change in the Action Keyword class, it is the same as in the last chapter.

Driver Script Class:

package executionEngine;

import java.lang.reflect.Method;
import config.ActionKeywords;
import utility.ExcelUtils;

public class DriverScript {
	//This is a class object, declared as 'public static'
	//So that it can be used outside the scope of main[] method
	public static ActionKeywords actionKeywords;
	public static String sActionKeyword;
	//This is reflection class object, declared as 'public static'
	//So that it can be used outside the scope of main[] method
	public static Method method[];

	//Here we are instantiating a new object of class 'ActionKeywords'
	public DriverScript() throws NoSuchMethodException, SecurityException{
		actionKeywords = new ActionKeywords();
		//This will load all the methods of the class 'ActionKeywords' in it.
                //It will be like array of method, use the break point here and do the watch
		method = actionKeywords.getClass().getMethods();
	}

    public static void main(String[] args) throws Exception {

    	//Declaring the path of the Excel file with the name of the Excel file
    	String sPath = "D://Tools QA Projects//trunk//Hybrid Keyword Driven//src//dataEngine//DataEngine.xlsx";

    	//Here we are passing the Excel path and SheetName to connect with the Excel file
        //This method was created in the last chapter of 'Set up Data Engine' 		
    	ExcelUtils.setExcelFile(sPath, "Test Steps");

    	//Hard coded values are used for Excel row & columns for now
    	//In later chapters we will use these hard coded value much efficiently
    	//This is the loop for reading the values of the column 3 (Action Keyword) row by row
		//It means this loop will execute all the steps mentioned for the test case in Test Steps sheet
    	for (int iRow = 1;iRow <= 9;iRow++){
		    //This to get the value of column Action Keyword from the excel
    		sActionKeyword = ExcelUtils.getCellData(iRow, 3);
            //A new separate method is created with the name 'execute_Actions'
			//You will find this method below of the this test
			//So this statement is doing nothing but calling that piece of code to execute
    		execute_Actions();
    		}
    	}
	
	//This method contains the code to perform some action
	//As it is completely different set of logic, which revolves around the action only,
	//It makes sense to keep it separate from the main driver script
	//This is to execute test step (Action)
    private static void execute_Actions() throws Exception {
		//This is a loop which will run for the number of actions in the Action Keyword class 
		//method variable contain all the method and method.length returns the total number of methods
		for(int i = 0;i < method.length;i++){
			//This is now comparing the method name with the ActionKeyword value got from excel
			if(method[i].getName().equals(sActionKeyword)){
				//In case of match found, it will execute the matched method
				method[i].invoke(actionKeywords);
				//Once any method is executed, this break statement will take the flow outside of for loop
				break;
				}
			}
		}
 }

The above code is now much more clear and simple. If there is any addition of method in Action Keyword class, driver script will not have any effect of it. It will automatically consider the newly created method.

Set Up Data Engine - Apache POI (Excel)
Set Up Data Engine - Apache POI (Excel)
Previous Article
Set Up Java Constant Variables
Set Up Java Constant Variables
Next Article
Lakshay Sharma
I’M LAKSHAY SHARMA AND I’M A FULL-STACK TEST AUTOMATION ENGINEER. Have passed 16 years playing with automation in mammoth projects like O2 (UK), Sprint (US), TD Bank (CA), Canadian Tire (CA), NHS (UK) & ASOS(UK). Currently, I am working with RABO Bank as a Chapter Lead QA. I am passionate about designing Automation Frameworks that follow OOPS concepts and Design patterns.
Reviewers
Virender Singh's Photo
Virender Singh

Similar Articles

Feedback