By Test Designing we mean to make a plan for implementing tests and techniques is the method of implementing that test plans. So, Test Design is nothing but to create a set of inputs to get the set of expected outputs. Various elements involved in designing a test. Let’s understand some of the important elements which help us in designing a framework. We will learn following topics in this article:
-
Page Object Model (POM).
-
Architecture of POM.
-
POM Example
-
Data driven using Excel.
-
Parameterization.
-
Log4j Logging
-
Exception handling.
-
Screen Capturing.
Page Object Model
Selenium interacts with the web-elements with the help of IDs, Class, names, XPaths etc. For accessing web elements every time we need to get the element’s properties and write into our code to access it. To make coding feasible we use Object Repository (OR). Object Repository is a centralized location where we can store objects information, it acts as interface between Test script and application in order to identify the objects during the execution. Selenium has no inbuilt object repository (OR) like QTP. Hence we need to create an OR which could be available when needed and also which is maintainable.
Page Object Model (POM) is a popular design pattern to create an object repository in selenium. Each of the web element properties are stored in a single class file.
Architecture of POM
Objects are created for each one of the pages and methods are developed exclusively to access to those objects. Let us use http://calculator.net for understanding the same. There are various calculators associated with it and each one of those objects in a particular page is created in a separate class file as static methods and they all are accessed through the 'tests' class file in which a static method would be accessing the objects.
Example
Let us understand it by implementing POM .
Step 1:
Create a simple class (page_objects_pcent_calc.java) file within a package and create methods for each one of those objects identifiers as shown below.
import org.openqa.selenium.*; public class page_objects_pcent_calc { private static WebElement element = null; // Math Calc Link public static WebElement lnk_math_calc(WebDriver driver) { element =driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")); return element; } // Percentage Calc Link public static WebElement lnk_percent_calc(WebDriver driver) { element = driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")); return element; } // Number 1 Text Box public static WebElement txt_num_1(WebDriver driver) { element = driver.findElement(By.id("cpar1")); return element; } // Number 2 Text Box public static WebElement txt_num_2(WebDriver driver) { element = driver.findElement(By.id("cpar2")); return element; } // Calculate Button public static WebElement btn_calc(WebDriver driver) { element = driver.findElement(By.xpath(".//*[@id='content']/table[1]/tbody/tr[2]/td/input[2]")); return element; } // Result public static WebElement web_result(WebDriver driver) { element = driver.findElement(By.xpath(".//*[@id='content']/p[2]/font/b")); return element; } } | |
Step 2:
Create a class with main and import the package and create methods for each one of those objects identifiers as shown below.
import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Demo_Web_Elements { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Launch website driver.navigate().to("http://www.calculator.net"); // Maximize the browser driver.manage().window().maximize(); // Use page Object library now page_objects_pcent_calc.lnk_math_calc(driver).click(); page_objects_pcent_calc.lnk_percent_calc(driver).click(); page_objects_pcent_calc.txt_num_1(driver).clear(); page_objects_pcent_calc.txt_num_1(driver).sendKeys("10"); page_objects_pcent_calc.txt_num_2(driver).clear(); page_objects_pcent_calc.txt_num_2(driver).sendKeys("50"); page_objects_pcent_calc.btn_calc(driver).click(); String result = page_objects_pcent_calc.web_result(driver).getText(); if(result.equals("5")) { System.out.println(" The Result is Pass"); } else { System.out.println(" The Result is Fail"); } driver.close(); } } | |
Output
The test is executed and the result is printed in the console. Given below is the snapshot of the same.
Data Driven Using Excel
Parameterizing is the important aspect of any programming language. While designing a test in selenium, we invite parameterizing for our tests. We will use Apache POI – Excel JAR for the same. This JAR helps us to read and write excel.
Step 1:
Navigate to the URL - http://poi.apache.org/download.html and download Zip.
Step 2:
Unzip the content.
Step 3:
Now create a project and add all the ‘External JARs’ .
Step 4:
Also add all ‘External JARs’ under the ‘ooxml-lib’ and ‘lib’ folder.
Step 5:
The Package Explorer is displayed as shown below. Apart from that, add 'WebDriver' related JAR's.
Parameterization
For demonstration, we will parameterize the Excel file by reading and writing excel.
Step 1:
We will parameterize all the inputs required for using Excel. The designed Excel is shown below.
Step 2:
Execute all functions for all the specified parameters.
Step 3:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelRead { public void readExcel(String filePath,String fileName,String sheetName) throws IOException{ //Create a object of File class to open xlsx file File file = new File(filePath+"\\"+fileName); //Create an object of FileInputStream class to read excel file FileInputStream inputStream = new FileInputStream(file); Workbook Workbook = null; //Find the file extension by spliting file name in substring and getting only extension name String fileExtensionName = fileName.substring(fileName.indexOf(".")); //Check condition if the file is xlsx file if(fileExtensionName.equals(".xlsx")){ //If it is xlsx file then create object of XSSFWorkbook class Workbook = new XSSFWorkbook(inputStream); } | |
Let us create generic methods to access the Excel file using the imported JARs. These methods help us get a particular cell data or to set a particular cell data, etc.
//Check condition if the file is xls file else if(fileExtensionName.equals(".xls")){ //If it is xls file then create object of XSSFWorkbook class Workbook = new HSSFWorkbook(inputStream); } //Read sheet inside the workbook by its name Sheet guru99Sheet = Workbook.getSheet(sheetName); //Find number of rows in excel file int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum(); //Create a loop over all the rows of excel file to read it for (int i = 0; i < rowCount+1; i++) { Row row = guru99Sheet.getRow(i); //Create a loop to print cell values in a row for (int j = 0; j < row.getLastCellNum(); j++) { //Print excel data in console System.out.print(row.getCell(j).getStringCellValue()+"|| "); } System.out.println(); } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Create a object of ReadGuru99ExcelFile class ExcelRead objExcelFile = new ExcelRead(); //Prepare the path of excel file //String filePath = System.getProperty("user.dir")+"\\src\\excelExportAndFileIO"; //Call read file method of the class to read data objExcelFile.readExcel("E:\\","Book1.xlsx","Sheet1"); } } | |
Output
Step 4:
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class writeExcel { public void writingExcel(String filePath,String fileName,String sheetName,String[] dataToWrite) throws IOException{ //Create a object of File class to open xlsx file File file = new File(filePath+"\\"+fileName); //Create an object of FileInputStream class to read excel file FileInputStream inputStream = new FileInputStream(file); Workbook Workbook = null; //Find the file extension by spliting file name in substing and getting only extension name String fileExtensionName = fileName.substring(fileName.indexOf(".")); //Check condition if the file is xlsx file if(fileExtensionName.equals(".xlsx")){ //If it is xlsx file then create object of XSSFWorkbook class Workbook = new XSSFWorkbook(inputStream); } | |
Let us learn how to read an excel file.
//Check condition if the file is xls file else if(fileExtensionName.equals(".xls")){ //If it is xls file then create object of XSSFWorkbook class Workbook = new HSSFWorkbook(inputStream); } //Read excel sheet by sheet name Sheet sheet = Workbook.getSheet(sheetName); //Get the current count of rows in excel file int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum(); //Get the first row from the sheet Row row = sheet.getRow(0); //Create a new row and append it at last of sheet Row newRow = sheet.createRow(rowCount+1); //Create a loop over the cell of newly created Row for(int j = 0; j < row.getLastCellNum(); j++){ //Fill data in row Cell cell = newRow.createCell(j); cell.setCellValue(dataToWrite[j]); } //Close input stream inputStream.close(); //Create an object of FileOutputStream class to create write data in excel file FileOutputStream outputStream = new FileOutputStream(file); //write data in the excel file Workbook.write(outputStream); //close output stream outputStream.close(); | |
} public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Create an array with the data in the same order in which you expect to be filled in excel file String[] valueToWrite = {"Mr. x","Goa"}; //Create an object of current class writeExcel objExcelFile = new writeExcel(); //Write the file using file name , sheet name and the data to be filled objExcelFile.writingExcel("E:\\","Book1.xlsx","Sheet1",valueToWrite); } } | |
Output
Log4j Logging
Log4j is a fast, flexible and reliable logging framework. Log4j is an audit logging framework that gives information about what has happened during execution. It offers the following advantages:
· Enables us to understand the application run.
· Log output can be saved that can be analyzed later.
· Helps in debugging, in case of test automation failures.
· Can also be used for auditing purposes to look at the application's health.
Components
1. Instance of Logger class.
2. Log level methods used for logging the message as one of the following:
a. Error
b. Warn
c. Info
d. Debug
e. Log
Example
Step 1:
Download Log4j JARs from https://logging.apache.org/log4j/1.2/download.html
Step 2:
Make a new project and add ‘External JARs’ from the extracted ‘apache-log4j-1.2.17’ of zip file downloaded from the previous step.
Step 3:
Also add all the Selenium support JARs.
Step 4:
Add a new XML file using we can specify the Log4j properties by right-clicking on project Folder >> new >> File
Name the file as ‘Log4j.properties’.
Step 5:
The final folder structure is shown below.
Step 6:
Now add the properties of Log4j which would be picked up during execution.
Step 7:
Create a main class and copy the following code.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.apache.log4j.Logger; public class LoggingDemo { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub WebDriver driver = new FirefoxDriver(); Logger log = Logger.getLogger("devpinoyLogger"); | |
driver.get("<a href="http://healthunify.com/bmicalculator/">http://healthunify.com/bmicalculator/</a>"); log.debug("opening webiste"); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); log.debug("entring weight"); driver.findElement(By.name("wg")).sendKeys("87"); log.debug("selecting kilograms"); driver.findElement(By.name("opt1")).sendKeys("kilograms"); log.debug("selecting height in feet"); driver.findElement(By.name("opt2")).sendKeys("5"); log.debug("selecting height in inchs"); driver.findElement(By.name("opt3")).sendKeys("10"); log.debug("Clicking on calculate"); driver.findElement(By.name("cc")).click(); log.debug("Getting SIUnit value"); String SIUnit = driver.findElement(By.name("si")).getAttribute("value"); log.debug("Getting USUnit value"); String USUnit = driver.findElement(By.name("us")).getAttribute("value"); log.debug("Getting UKUnit value"); String UKUnit = driver.findElement(By.name("uk")).getAttribute("value"); log.debug("Getting overall description"); String note = driver.findElement(By.name("desc")).getAttribute("value"); System.out.println("SIUnit = " + SIUnit); System.out.println("USUnit = " + USUnit); System.out.println("UKUnit = " + UKUnit); System.out.println("note = " + note); driver.quit(); } } | |
In the above code, we visit http://healthunify.com/bmicalculator/and verify BMI calculator. The weight entered is 87KG and the height is 5 Feet 10 inches. The script checks output in SE, US and UK units.
Using Logger.getLogger("devpinoyLogger") we create system level logs
Using log.debug method we store data into Manual.log
Step 8:
Run the script. Open the location of Manual and Selenium logs to check logging data.
Exception Handling
When we are developing tests, we should ensure that the scripts can continue their execution even if the test fails. An unexpected exception would be thrown if the worst case scenarios are not handled properly.
If an exception occurs due to an element not found or if the expected result doesn't match with actuals, we should catch that exception and end the test in a logical way rather than terminating the script abruptly.
Syntax
The actual code should be placed in the try block and the action after exception should be placed in the catch block. Note that the 'finally' block executes regardless of whether the script had thrown an exception or NOT.
try
{
// Perform Action
}
catch(ExceptionType1 exp1)
{
// Catch block 1
}
catch(ExceptionType2 exp2)
{
// Catch block 2
}
catch(ExceptionType3 exp3)
{
// Catch block 3
}
finally
{
// The finally block always executes.
}
Screen Capturing
This functionality helps to grab screenshots at runtime when required, in particularly when a failure happens. With the help of screenshots and log messages, we will be able to analyze the results better.
Screenshots are configured differently for local executions and Selenium Grid (remote) executions. Let us take a look at each one of them with an example.
Localhost Execution
import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; public class webdriverdemo { public static void main(String[] args) throws IOException { WebDriver driver = new FirefoxDriver(); | |
In the following example, we will take a screenshot after calculating the percentage. Ensure that you give a valid path to save the screenshot.
// Puts an Implicit wait, Will wait for 10 seconds // before throwing exception driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Launch website driver.navigate().to("http://www.calculator.net/"); // Maximize the browser driver.manage().window().maximize(); // Click on Math Calculators driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click(); // Click on Percent Calculators driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click(); // Enter value 10 in the first number of the percent Calculator driver.findElement(By.id("cpar1")).sendKeys("10"); // Enter value 50 in the second number of the percent Calculator driver.findElement(By.id("cpar2")).sendKeys("50"); // Click Calculate Button driver.findElement(By.xpath(".//*[@id='content']/table /tbody/tr/td[2]/input")).click(); // Get the Result Text based on its xpath String result = driver.findElement(By.xpath(".//*[@id='content']/p[2] /span/font/b")).getText(); File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("D:\\screenshots\\screenshots1.jpg")); // Print a Log In message to the screen | |
System.out.println(" The Result is " + result); // Close the Browser. driver.close(); } } | |
As a output the image file containing the desired screen shot will be generated.
What’s next?
In next article we will learn Selenium Grid.
No comments:
Post a Comment