Selenium Testing - SPLessons

Selenium Test Design

Home > Lesson > Chapter 14
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Selenium Test Design

Selenium Test Design

shape Description

Selenium Test Design, Software Testing Technique is a procedure to choose the test cases. Using techniques enough number of test cases can be known to achieve the task.  There are many segments included in planning the tests. The important parts for planning a structure are

Log4j Logging

shape Description

Selenium Test Design - Logging is a vital piece of programming that supports for latest investigating facilities and organized association of data recorded at the execution time. It gives a successful procedure to track the mistakes that happens in the application, after the convey process it is useful to comprehend what turned out badly with application. Warn, log, error, debug, info are the log level methods.  

shape Examples

Taking calculator as a example for this technique

shape Step1

Drive to this URL Download log4j file

shape Step2

Launch Eclipse and create new Java project and click next button

shape Step3

Click Add External Jar and add 'Log4j-1.2.17.jar', Selenium WebDriver Libraries and Selenium WebDriver JAR's located in the Libs folder

shape Step4

Include a New XML document utilizing which we can indicate the Log4j properties and click finish button

shape Step5

Here log4j.xml file is created

shape Step6

Presently include the properties of Log4j which would be selected at the execution [java] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"> <appender name="fileAppender" class="org.apache.log4j.FileAppender"> <param name="Threshold" value="INFO" /> <param name="File" value="percent_calculator.log"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%c] (%t:%x) %m%n" /> </layout> </appender> <root> <level value="INFO"/> <appender-ref ref="fileAppender"/> </root> </log4j:configuration> [/java] To append the logging data into a particular document user has to use org.apache.log4j.FileAppender. The Logger component grants logging instructions such as logger.debug(), logger.error() etc calls and revert them to appropriate destinations to the Appenders.

shape Step 7

Presently for exhibition reason, join log4j in the same test that have been performing . Include a class document in the 'Main' function [java] //this code for Selenium Test Design package log4j; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; public class log4jtest { static final Logger logger = LogManager.getLogger(log4jtest.class.getName()); public static void main(String[] args) { DOMConfigurator.configure("log4j.xml"); logger.info("Log4j is begining....."); WebDriver webdrvr = new FirefoxDriver(); //Puts a Implicit wait, Will wait for 5 seconds before throwing exception webdrvr.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //Install website webdrvr.navigate().to("http://www.calculator.net/"); logger.info("Open Calc Application"); //Enlarge the browser webdrvr.manage().window().maximize(); //Tick on Math Calculators webdrvr.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click(); logger.info("Clicked Math Calculator Link"); //Tick on Percent Calculators webdrvr.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click(); logger.info("Clicked Percent Calculator Link"); //Give value 75 in the initial number of the percent Calculator webdrvr.findElement(By.id("cpar1")).sendKeys("75"); logger.info("Entered Value into First Text Box"); //Give value 100 in the second number of the percent Calculator webdrvr.findElement(By.id("cpar2")).sendKeys("100"); logger.info("Entered Value into Second Text Box"); //Tick Calculate Button webdrvr.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click(); logger.info("Click Calculate Button"); //Get the output Text based on its xpath String output = webdrvr.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText(); logger.info("Get Text Value"); //Print a Log In message to the screen logger.info(" The Output is " + output); if(output.equals("5")) { logger.info("The output is Pass"); } else { logger.error("Log4J testing failed "); } logger.info("======================= "); //Close the Browser. webdrvr.close(); } } [/java] As every one know that log4j is fast and comfortable API and it was totally coded in JAVA, which was spreaded under Apache licence and it also has the feature that it can be portable to the other languages such as C, C++, Python, etc. The DOMConfigurator.configure() is used to configure the XML file as follows. [java]DOMConfigurator.configure("log4j.xml");[/java] Puts a Implicit wait, Will wait for 5 seconds before throwing exception. [java]webdrvr.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); [/java] To locate the elements user need to write the code that SPlessons have already discussed in locating element chapter. The XPath is nothing but a dialect that utilized for XML document to locate the nodes, one can use the XPath when thers is no id or name element to locate, these locators can be used to declare elements via using attributes. [java]webdrvr.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();[/java] To test the result in the IDE user has to write some mathematical logic why because here used the web site related to calculation. [java] if(output.equals("5")) { logger.info("The output is Pass"); } else { logger.error("Log4J testing failed "); }[/java]

shape Step 8

Upon execution, the log document is made on the root envelope as demonstrated as follows.  Document Cannot be find the in Eclipse, open 'Windows Explorer' to demonstrate the same.

shape Step 9

The content of the document is demonstrated below

Multi Browser Testing

shape Description

Multi Browser Testing is required to perform multi-program testing to watch that the usefulness is working as indicated by the specification with each program.

shape Examples

Here getting the  default sum value from xe.com cash converter in every single current program at the same time

shape Step 1

write the code to implement the example [java] //this code for Selenium Test Design import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.testng.annotations.*; public class AllBrowsersTest { private WebDriver driver; private String URL = "http://www.xe.com"; @Parameters("browser") @BeforeTest public void testInBrowsers(String browser) { if (browser.equalsIgnoreCase("firefox")) { System.out.println("Testing with Firefox"); driver = new FirefoxDriver(); driver.get(URL); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); } else if (browser.equalsIgnoreCase("chrome")) { System.out.println("Testing with Chrome"); System.setProperty("webdriver.chrome.driver", "c:\\selenium\\drivers\\chromedriver.exe"); driver = new ChromeDriver(); driver.get(URL); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); } else if (browser.equalsIgnoreCase("ie")) { System.out.println("Testing with Internet Explorer"); System.setProperty("webdriver.ie.driver", "c:\\selenium\\drivers\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.get(URL); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); } else { throw new IllegalArgumentException("The Browser Type is Undefined"); } } @Test public void findDefaultAmountFieldValue() { WebElement element = driver.findElement(By.xpath(".//*[@id='amount']")); String result = element.getAttribute("value"); if(result.equals("1")){ System.out.println("Default value in amount field is 1"); } else { System.out.println(" Default value in amount field is not 1"); } } @AfterTest public void closeBrowser() { driver.close(); } } [/java] Here also used the same logic as above program, but here used multi browsers as follows. [java] if (browser.equalsIgnoreCase("firefox")) { System.out.println("Testing with Firefox"); } else if (browser.equalsIgnoreCase("chrome")) { System.out.println("Testing with Chrome"); } [/java] Puts a Implicit wait, Will wait for 5 seconds before throwing exception. [java]webdrvr.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); [/java] The XPath is nothing but a dialect that utilized for XML document to locate the nodes, one can use the XPath when thers is no id or name element to locate. [java]webdrvr.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();[/java]

shape Step 2

To characterize the request of the tests, need to make a XML (testing.xml) record posting the test strategies that might want to run. Ensure that the test strategies are clarified with @Test, or else the TestNG motor won't summon them by any stretch of the imagination. To run parallel need to specify parallel="tests" as appeared

shape Step 3

XML file is created for the tests. [java] <suite name="XE default value test" verbose="10" parallel="tests"> <test name="Test with firefox" preserve-order="true"> <parameter name="browser" value="firefox" /> <classes> <class name="AllBrowsersTest" /> </classes> </test> <test name="Test with chrome" preserve-order="true"> <parameter name="browser" value="chrome" /> <classes> <class name="AllBrowsersTest" /> </classes> </test> <test name="Test with internet explorer" preserve-order="true"> <parameter name="browser" value="ie" /> <classes> <class name="AllBrowsersTest" /> </classes> </test> </suite> [/java]

shape Step 4

Execute as TestNG Suite as demonstrated as follows. If it's not too much trouble note: you should introduce TestNG module for eclipse IDE before it run.

shape Step 5

The programs (firefox, chrome, web traveler) will be propelled at the same time and the outcome will be printed in the console window

Page Object Model

shape Description

Page Object Model is an outline example which is utilized to make Object Repository for UI components of site page. This Page class will discover the web elements of that site page furthermore contains Page strategies which perform operations on those web elements.

Advantages

shape Description

Following are the advantages of Page Object Model:
  • Page Object Patten says operations and streams in the UI ought to be isolated from check. This idea makes our code cleaner and straightforward.
  • The object store is free of test cases, so the same item storehouse can be utilized for an alternate reason furthermore it supports for various instruments.
  • As a result of the reusable page techniques in the POM classes the code turns out to be less and upgraded.
  • Techniques get more practical names which can be effortlessly mapped with the operation happening in UI.

Parameterizing using Excel

shape Description

By frequently create a  document, open it and upgrade something or erase it. Comparable it requires a procedure to control records utilizing Selenium. To peruse or compose an Excel, Apache give a library POI. This library is skilled to peruse and compose both XLS and XLSX record organization of exceed expectations.

shape Step 2

Extract the downloaded files and add those files by add external jar a

shape Step 3

Additionally add all jar documents under lib organizer of removed poi envelope as well

shape Step 4

For exhibit,parameterize the percent number calculator test.Here parameterize the all important information for percent calculator operation utilizing Excel as appeared

shape Step 5

By utilizing bland techniques we can get to the Excel record utilizing the foreign made JARs. Presently we are making essential non specific techniques which get a particular cell information or to set a cell information and so forth. [java] import java.io.*; import org.apache.poi.xssf.usermodel.*; public class ExcelOB { private XSSFSheet excelSheet; private XSSFWorkbook excelWBook; public ExcelOB(String filePath, String sheetName) throws Exception { try { FileInputStream ExcelFile = new FileInputStream(filePath); excelWBook = new XSSFWorkbook(ExcelFile); excelSheet = excelWBook.getSheet(sheetName); } catch (Exception exp){ throw (exp); } } public int getRows() throws Exception { //Handling exception try{ return excelSheet.getPhysicalNumberOfRows(); } catch (Exception e){ throw (e); } } public String getCellValueAsString(int row, int col) throws Exception { //Handling exception try { String CellData = excelSheet.getRow(row).getCell(col).getStringCellValue(); return CellData; } catch (Exception e) { return "Cell Data cannot be extracted"; } } public double getCellDataAsDouble(int row, int col) throws Exception { //Handling exception try { double CellData = excelSheet.getRow(row).getCell(col).getNumericCellValue(); return CellData; } catch (Exception e){ return 0.00; } } } [/java] File input stream is used to get the bytes from a document in a particular directory, this class is used to read the streams of raw bytes like image information. [java]FileInputStream ExcelFile = new FileInputStream(filePath);[/java] Where the developer used exception handling strategy because while getting the information from the system regarding excel sheet error may be occurred, as every one know that try block is used to place the exception area, catch block is used to describe the exception . [java] try{ return excelSheet.getPhysicalNumberOfRows(); } catch (Exception e){ throw (e); } [/java]

shape Step 5

To get to the made Excel strategies, require another analyzer class with primary technique as demonstrated as follows. [java] import java.io.*; import org.apache.poi.xssf.usermodel.*; public class ExcelOB { private XSSFSheet excelSheet; private XSSFWorkbook excelWBook; public ExcelOB(String filePath, String sheetName) throws Exception { try { FileInputStream ExcelFile = new FileInputStream(filePath); excelWBook = new XSSFWorkbook(ExcelFile); excelSheet = excelWBook.getSheet(sheetName); } catch (Exception exp){ throw (exp); } } public int getRows() throws Exception { //Handling exception try{ return excelSheet.getPhysicalNumberOfRows(); } catch (Exception e){ throw (e); } } public String getCellValueAsString(int row, int col) throws Exception { //Handling exception try { String CellData = excelSheet.getRow(row).getCell(col).getStringCellValue(); return CellData; } catch (Exception e) { return "Cell Data cannot be extracted"; } } public double getCellDataAsDouble(int row, int col) throws Exception { //Handling exception try { double CellData = excelSheet.getRow(row).getCell(col).getNumericCellValue(); return CellData; } catch (Exception e){ return 0.00; } } } [/java]

shape Step 6

Above will deliver results as demonstrated as follows

Capture Screenshots

shape Description

While running tests utilizing Selenium Webdriver, there might be a few circumstances to take screenshot for the fizzled test ventures for appropriate bug reporting. The screenshot can be catch depend upon the route planned in the Test Framework, either for immeasurably vital test steps or simply the fizzled ones and so on

shape Step 1

The code underneath takes the screenshot of the page and saves it to framework [java] import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Screenshots { public static void main(String[] args) throws Exception { WebDriver driver = new FirefoxDriver(); driver.get("http://www.xe.com"); File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("c:\\selenium\\tests\\xe_home_screenshot.jpg")); System.out.println("XE.com screenshot was successful"); driver.close(); } } [/java]

shape Step 2

Also the caught screenshot will appear like this

Capture Videos

shape Description

We will figure out how to catch video, since log record or a screenshot are insufficient to investigate the disappointments Download jar file

shape Step 1

Add jar file to venture libraries

shape Step 2

Implement the code to catch a video of the straightforward test execution. [java]import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.awt.*; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import org.monte.media.math.Rational; import org.monte.media.Format; import org.monte.screenrecorder.ScreenRecorder; import static org.monte.media.AudioFormatKeys.*; import static org.monte.media.VideoFormatKeys.*; public class webdriverdemo { private static ScreenRecorder screenRecorder; public static void main(String[] args) throws IOException, AWTException { GraphicsConfiguration gconfig = GraphicsEnvironment .getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); screenRecorder = new ScreenRecorder(gconfig, new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI), new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, DepthKey, (int)24, FrameRateKey, Rational.valueOf(15), QualityKey, 1.0f, KeyFrameIntervalKey, (int) (15 * 60)), new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey,"black", FrameRateKey, Rational.valueOf(30)), null); WebDriver driver = new FirefoxDriver(); // Begin Capturing the Video screenRecorder.start(); // Puts an Implicit hold up, Will sit tight for 5 seconds before tossing exemption driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Install website driver.navigate().to("http://www.calculator.net/"); // Maximize the browser driver.manage().window().maximize(); // press 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(); // Give value 20 in the first number of the percent Calculator driver.findElement(By.id("cpar1")).sendKeys("10"); // Give value 100 in the second number of the percent Calculator driver.findElement(By.id("cpar2")).sendKeys("50"); // Press 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(); // Stop the ScreenRecorder screenRecorder.stop(); } } [/java]

shape Step 3

The video recorded is stored in pc

Summary

shape Key Points

  • Selenium Test Design - Using test design techniques, more number of defects can be identified.
  • Selenium Test Design - To improve the quality and productivity of software application.
  • In Log4j loggers are used to append the logging data.
  • By using appenders one can guide the system bout where to log on data.