We have created object repository In selenium webdriver data driven framework creation STEP 27. So now, our all web element's xpath or CSSPath or any other locators will be stored In object repository Instead of test cases files. Now let us try to compact webdriver code by creating getElementByXPath function to return web page element on demand.
Prerequisite : Previous 27 Steps Of WebDriver data driven framework creation listed on THIS PAGE should be Implemented.
I have created 2 getElementByXPath functions In SuiteBase.java class to get Its access In all test cases. First getElementByXPath function has only one Input parameter and second overloaded method has three Input parameters as bellow.
getElementByXPath(String) getElementByXPath(String, int, String)
- In first getElementByXPath function, You have to pass web element's xpath key value as Input. The code of this function will locate and return the element from web page If found. Else It will return null.
- In second getElementByXPath function, You have to pass web element's xpath key1(1st part of xpath), Integer Value and xpath key2(2nd part of xpath). These three Input parameters will create full XPath for web element and code of this function will locate and return element from the web page If found. Else It will return null.
You will find both these functions In SuiteBase.java class file when you download Step 28.zip folder at bellow.
How To Use getElementByXPath Function In Test Cases
If you have single key of xpath then you can use getElementByXPath function as bellow. It will click on button whose key Is 'btn_Plus' In Objects.properties object repository file.Example :
If you have to build dynamic xpath of element then you can use getElementByXPath function as bellow. Here we are sending 3 parameters to getElementByXPath function to build full xpath of element. btn_Calc_PrePart and btn_Calc_PostPart are static and will be retrieved from Objects.properties object repository file. ValueOne can be any Integer value so we can name It dynamic xpath generation.Example :
I have Implemented both these functions In SuiteOneCaseOne.java test case file to retrieve element from web page.
Download Required Files
You need to download SuiteOneCaseOne.java and SuiteBase.java modified files. You will get both these files In bellow given zip folder.
Extract the folder and replace SuiteOneCaseOne.java and SuiteBase.java files with existing files In eclipse.
Now you can run your test from .bat file and observe the execution. There Is not any flow change In this step but just observe that you are not getting any error during execution.
If you not understand how getElementByXPath function Is working then put break point In your test case and run your test In debug mode from testng.xml file and debug step by step execution. Let me know If you have any query In this step by commenting bellow.
What We Have Achieved In This Step