Sunday, September 15, 2013

Executing javascript using WebDriver

  You can execute required javascript call using WebDriver in your automation code using JavaScriptExecutor.

Example
  • you may want to fire an event on a particular element. (calling blur event directly)
  • you may want to execute some script which will do some other operation. (instead of clicking directly call onclick targeted script)
Steps
  • Cast the WebDriver instance to JavaScriptExecutor 
  • Execute the script using executeScript() method
WebDriver-JavaScriptExecutor
Logic

WebDriver driver = new FirefoxDriver();
JavaScriptExecutor js=(JavaScriptExecutor)driver;  //casting driver instance
String title=(String)js.executeScript("return document.title");  //for getting window tile
String name=(String)js.executeScript("return window.name");  //for getting window name
js.executeScript("$('#elementId').blur()");  //firing blur event on an element


executeScript() will return java.lang.Object, from that you can get your required data.


 While returning values from the JavaScript code, need to use the return keyword. Based on the type of return value, need to type cast the executeScript() method.



  • For decimal values, Double can be used, 
  • for non-decimal numeric values Long can be used,  
  • for Boolean values Boolean can be used. 
  • JavaScript code is returning an HTML element, then WebElement can be used. 
  • For text values, String can be used. 
  • If a list of objects is returned, then any of the values will work based on type of objects. Otherwise, a null will be returned.


Related Topics
Handling JavaScript Alerts
Taking Screenshots

Browser Navigation Using WebDriver





Browser Navigation.

Browser navigation
Do you want to automate any browser action (Ex: forward, back, refresh) using WebDriver ?

Cases where we need this type of operations

  • You need to verify your web-application going to previous page if you click on browser back button.
  • Sometimes you may want to refresh the browser to complete some action.
Its pretty simple with WebDriver. Here is the logic to do browser navigation operations.

//TO perform browser back button action
driver.navigate().back();
//TO perform browser forward button action
driver.navigate().forward();

//To refresh bowser
driver.navigate().refresh();

//To navigate to particular URL
driver.navigate().to("url");
//You can give url in String or java.net.URL url format


I hope this would be helpful for beginners.


Regards,
SantoshSarma 


Related Topics
Selecting options from dropdown
Selecting options from dropdown using partial text


Handling JavaScript alerts using WebDriver

   It is very simple to handle javascript alerts in WebDriver. If we don't handle the alerts properly WebDriver will throw UnhandledAlertException .

Handling javascript alerts
  In web application mostly we see two types of pop-ups, 1. alerts 2. confirm popup




  Handling both alerts & confirms popup WebDriver has a Alert interface. Using WebDriver you can click on OK or Cancel button and also can get alert message also to verify.

Logic 

//First we need switch the control to alert.
       Alert alert = driver.switchTo().alert();

//Getting alert text
       alert.getText();

//Click on OK
       alert.accept();

//Click ok Cancel
      alert.dismiss();



I hope this would help you to handle javascript alerts.

Happy coding :)

Regards,
SantoshSarma


Related topics
Executing Java script using selenium


Saturday, September 14, 2013

Locating WebElements Using XPath







   In automation locating web elements in DOM is one of the important task. In DOM, if all the elements have unique ids then no problem but, if not we need to go for xpath for locating elements in DOM.

  Say for example generally we don't see any ids for the table rows & columns, in that case we need to locate table data using some other attributes. Ex: name, position, innerText.

  Below I'm writing simple example to understand the different options available in xpath. (Place mouseover the locator to see which element it will locate in table)

HTML Elements


Above html in browser

One Bike
Two Car
Three Bus
Four Jeep

Locating elements using Attributes

AttributeUsage
idBy.xpath("//table[@id='tableId']")
idBy.xpath("//td[@id='car']")
nameBy.xpath("//td[@name='Chk3']")


Locating Rows using index

RowAs a child As a sub-child
1By.xpath("//table[@id='tableId']/tbody/tr[1]")By.xpath("//table[@id='tableId']//tr[1]")
2By.xpath("//table[@id='tableId']/tbody/tr[2]")By.xpath("//table[@id='tableId']//tr[2]")
3By.xpath("//table[@id='tableId']/tbody/tr[3]")By.xpath("//table[@id='tableId']//tr[3]")
4By.xpath("//table[@id='tableId']/tbody/tr[4]")By.xpath("//table[@id='tableId']//tr[4]")

Locating Rows using functions

FunctionAs a child
position()By.xpath("//table[@id='tableId']//tr[position()=1]")
position()By.xpath("//table[@id='tableId']//tr[position()=3]")
last()By.xpath("//table[@id='tableId']//tr[last()]")
last()By.xpath("//table[@id='tableId']//tr[last()-1]")

Locating Rows using String functions

FunctionUsage
text()By.xpath("//table[@id='tableId']//tr/td[text()='One']")
contains()By.xpath("//table[@id='tableId']//tr/td[contains(text(),'hre')]")
starts-with()By.xpath("//table[@id='tableId']//tr/td[start-with(text(),'Fo')]")

Locating Columns using Xpath Axes

AxesUsage
childBy.xpath("//table[@id='tableId']//tr/child::td[text()='One']")
parentBy.xpath("//td[@id='car']/parent::tr")
preceding-siblingBy.xpath("//td[contains(@id,'bus')]/preceding-sibling::td/input")
following-siblingBy.xpath("//td[text()='Four']/following-sibling::td[@id='jeep']")
  • Child : Selects all children of the current node.
  • Parent : Selects the parent of the current node.
  • preceding-sibling:Selects all siblings before the current node.
  • following-sibling:Selects all siblings after the current node.

Happy Coding :)


Regards,
SantoshSarma



Friday, September 13, 2013

Generating Random Data





Generating Random Data
Say , you are running RecordCreate/FormFilling automation for 100 times.
  1. Passing every time same values (Hardcoded values)
  2. Passing randomly generated values from allowed characters
Which one is more reliable ? 

How will you verify forms by filling allowed max length values ?


Let's see how to fill the forms in web application with random & specified length values.

Consider below form

You want to fill below form with randomly generated values with specified lengths.

Register here

First Name
Last Name
Email
Phone
Income


See below testcase to know how can we pass random & specified length values to different fields.

RegistrationForm.java


package com.test.registration;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.test.general.GenerateData;

public class RegistrationForm {
 
 WebDriver driver;
 GenerateData genData;
 
 @Before
 public void before(){
  driver=new FirefoxDriver();
  genData=new GenerateData();
 }
 
 @Test
 public void testRegistrationForm() {
  driver.findElement(By.id("f_name")).sendKeys(genData.generateRandomAlphaNumeric(30));    
  driver.findElement(By.id("l_name")).sendKeys(genData.generateRandomString(20));
  driver.findElement(By.id("email")).sendKeys(genData.generateEmail(30));
  driver.findElement(By.id("skype")).sendKeys(genData.generateStringWithAllobedSplChars(30, "abc123_-."));
  driver.findElement(By.id("phone")).sendKeys(genData.generateRandomNumber(10));
  driver.findElement(By.id("income")).sendKeys(genData.generateRandomNumber(9));
  driver.findElement(By.id("submit")).click();
  assertEquals("Success", driver.getTitle());
 }
 
 @After
 public void after(){
  driver.quit();
 }

}




GenerateData.java


package com.test.general;

import org.apache.commons.lang3.RandomStringUtils;

public class GenerateData {

 public String generateRandomString(int length){
  return RandomStringUtils.randomAlphabetic(length);
 }
 
 public String generateRandomNumber(int length){
  return RandomStringUtils.randomNumeric(length);
 }
 
 public String generateRandomAlphaNumeric(int length){
  return RandomStringUtils.randomAlphanumeric(length);
 }
 
 public String generateStringWithAllobedSplChars(int length,String allowdSplChrs){
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    allowdSplChrs;
  return RandomStringUtils.random(length, allowedChars);
 }
 
 public String generateEmail(int length) {
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    "_-.";   //special characters
  String email="";
  String temp=RandomStringUtils.random(length,allowedChars);
  email=temp.substring(0,temp.length()-9)+"@test.org";
  return email;
 }
 
 public String generateUrl(int length) {
  String allowedChars="abcdefghijklmnopqrstuvwxyz" +   //alphabets
    "1234567890" +   //numbers
    "_-.";   //special characters
  String url="";
  String temp=RandomStringUtils.random(length,allowedChars);
  url=temp.substring(0,3)+"."+temp.substring(4,temp.length()-4)+"."+temp.substring(temp.length()-3);
  return url;
 }
}
 

    While doing web application automation make a habit of passing random data with different lengths (<= Allowed max length) every time to improve reliability.


Related Topics
Generating Dynamic Dates