Monday, October 14, 2013

Scroll Function in WebDriver

Sometimes we would like to scroll webpage to particular WebElement or press Keyboard DOWN button to scroll the page. We can achieve scroll pages with below code snippets. 

Scrolling Using javascript

Code :

       WebElement ele = driver.findElement(By.id("test"));
       ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView()",ele);

Using Actions Class

package name  : org.openqa.selenium.interactions.Actions

java code :

                          Actions action=new Actions(driver);
                          action.sendKeys(Keys.DOWN).perform();

Without Using Actions Class

java code :

                     driver.findElement(By.tagName("body")).sendKeys(Keys.DOWN);



Related Topics





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



Saturday, April 20, 2013

Print table data






Locating table rows and cells
 Sometimes we need to iterate through out table and do some operations with that.

Example :

  1. Verify for expected values in table
  2. Sort  table columns in ascending & descending order and verify.
In above both the cases we need to get the table data to verify. Lets see how to get the data from table.
Steps
  • get table instance
  • using above table instance , get all table rows
  • iterate each row and get all columns values.
Logic


@Test
public void testTable()
{
          WebElement table = driver.findElement(By.id("tableId"));
       
          //Get all rows (tr tags)
          List<WebElement> rows = table.findElements(By.tagName("tr"));

           //Print data from each row (Data from each td tag)
           for (WebElement row : rows) {
           List
<WebElement> cols = row.findElements(By.tagName("td"));
                  for (WebElement col : cols) {
                        System.out.print(col.getText() + "\t");
                  }
          System.out.println();
          }
}


Happy Coding :)


Regards,
SantoshSarma




Saturday, April 6, 2013

Get Date..!


In many cases we want to use different dates (today's date / future date/ past date) with different formats.

Example:

  1. Task due date you want to fill 5 days from current date with dd-MM-yyyy format.
  2. You want to add today's date automatically to some field with MMM/dd/yy format.
  I'm just writing a java method which will take two arguments period (no of days) & format of date.

    For Getting today's date pass period as 0 , for getting future date pass period as positive and negative number for getting past date. 
<>
 Logic

public String getDate(int period,String format)
{
     Calendar currentDate = Calendar.getInstance();
     SimpleDateFormat formatter= new SimpleDateFormat(format);
     currentDate.add(Calendar.DAY_OF_MONTH, period);
     String date = formatter.format(currentDate.getTime());
     return date;
}
//Parameters :
//period : no of days gap between the current and desired date
//format : Format of the date (Ex : dd/MM/yyyy . yyyy MMM dd)

Output :
Current date & Time is :
No of days Format Output
0 "MM/dd/yyyy"
5 "MM/dd/yyyy"
-3 "MM/dd/yyyy"



Happy coding :)

Regards,
SantoshSarma

Choosing options from Dropdown - WebDriver






In web application we see many drop down lists for many input fields (Ex : gender, age, country..etc). This drop down option is different from normal text/numeric input field. It has separate tag <select></select>in html.

In automation while filling most of the forms we need to fill/select the drop down values also. For achieving this WebDriver has separate class called Select.

In this post we will see what are all different method available in Select class.

Consider below example

                  HTML CODE
                                         <select id="city">
                                               <option value="Op1">Chennai</option>
                                               <option value="Op2">Hyderabad</option>
                                               <option value="Op3">Bangalore</option>
                                         </select>

Select an Option
Available methods for selecting an option are
  1. selectByIndex(int index)
  2. selectByValue(java.lang.String value)
  3. selectByVisibleText(java.lang.String text)
selectByIndex(int index)
Select the option at the given index.
Usage :
new Select(driver.findElement(By.id("city"))).selectByIndex(2);
In above example it will select the Hyderabad because it is in index 2.

selectByValue(java.lang.String value)
Select all options that have a value matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByValue("Op3");
In above example it will select the Bangalore  based on the value attribute of that option.

selectByVisibleText(java.lang.String text)
Select all options that display text matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Chennai");
In above example it will select the Chennai based on the visible text.


De-select an option
Available methods for de-selecting an option(s) are,

  1. deselectAll()
  2. deselectByIndex(int index)
  3. deselectByValue(java.lang.String value)
  4. deselectByVisibleText(java.lang.String text)
deselectAll()
  • Clear all selected entries.
deselectByIndex(int index)
  • Deselect the option at the given index.
deselectByValue(java.lang.String value)
  • Deselect all options that have a value matching the argument.
deselectByVisibleText(java.lang.String text)
  • Deselect all options that display text matching the argument.


Getting all options
Some times we may in need to get all the options available in drop down list in that case below method will be useful.

  • getOptions();
getOptions()
It will return All options belonging to this select tag
Usage :
List<WebElement> allCities=new Select(driver.findElement(By.id("city"))).getOptions();
for(WebElement city:allCities)
{
      System.out.println(city.getText());    //It will return the text of each option
      System.out.println(city.getAttribute("value"));    //it will return the value attribute of each option
}

Get Selected Option(s)
If you want to verify whether the proper value got selected in particular drop down list you can make use of below methods.


  1. getFirstSelectedOption();
  2. getAllSelectedOptions() ;
getFirstSelectedOption();
  • The first selected option in this select tag (or the currently selected option in a normal select)
getAllSelectedOptions() ;
  • It will return List of All selected options belonging to this select tag. (This will be useful for multiselect picklist)

Handling multi-select pick list

                 HTML CODE
                                         <select id="city" multiple>
                                               <option value="Op1">Chennai</option>
                                               <option value="Op2">Hyderabad</option>
                                               <option value="Op3">Bangalore</option>
                                         </select>


Handling multi select pick list same as normal drop down( single pick list).
For selecting both Hyderabad, Bangalore option you need to use one of the below logics.

new Select(driver.findElement(By.id("city"))).selectByIndex(2);
new Select(driver.findElement(By.id("city"))).selectByIndex(3);
Or
new Select(driver.findElement(By.id("city"))).selectByvalue("Op2");
new Select(driver.findElement(By.id("city"))).selectByvalue("Op3");
Or
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Hyderabad");
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Bangalore");


I hope you understand WebDriver Select class usage in automation.


Happy Selecting :)


Regards,
SantoshSarma



Wednesday, March 27, 2013

Replace XPath with Css selector






If you know css selectors, those are much more easier (and will work fine with IE without any problem ) than xpath even though they can't replace entire xpath.


Consider below HTML tags


 <div id="firstDiv">This div tag has static id </div>

 <p id="paragraps_dynamic_1234">This p tag has dynamic id</p>

 <a onclick="doThat()" title="doThatOperation">This a tag has multiple attributes</a>

 <h1 name="heading1" value="headName">This is heading</h1>


<div>
<input type="text" id="username" name="username"
<input type="password" id="password" name="pwd"
</div>

<h2 id="propertyUserData">This tag is for starts-with example</h2>


Tag XPATH CSS SELECTOR
div "//div[@id='firstDiv']" "div[id='firstDiv']"
p "//p[contains(@id,'paragraps_dynamic_')]" "p[id*='paragraps_dynamic_']"
a "//a[contains(@onclick,'doThat') and @tile='doThatOperation']" "a[onclick*='doThat'][tile='doThatOperation']"
h1 "//h1[@name='heading1' and @value='headName']" "h1[name='heading1'][value='headName']"
input "//div/input[@id='username']" "div > input[id='username']"
input "//h2[starts-with(@id,'propertyUser')]" "h2[id^='propertyUser']"

By seeing above locators we can conclude some points regarding css selectors

  • Using css selector we can access particular node or immediate child of any node
  • Can combine as many conditions as we want for single node.
  • Can achieve starts-with, contains functionality using ^,* symbols respectively. 
  • We can't traverse back using css selector.
  • We can't go to  the siblings also (preceding as well as following)



Tuesday, March 26, 2013

Running JUnit test cases from cmd prompt





Running JUnit test cases from cmd prompt
For Running Junit 4.x test cases from command prompt you should use below command

java -cp C:\lib\junit.jar org.junit.runner.JUnitCore [test class name]

For running Junit 3.x test cases from command prompt you need use below command

java -cp /usr/java/lib/junit.jar junit.textui.TestRunner [test class name]

Example Program

TestCaseA.java

package test; import org.junit.Test; import org.junit.After; import org.junit.Before; public class TestCaseA { @Before public void beforeMethod() { System.out.println("Before method.."); } @Test public void JUnit4Test() { System.out.println("In test method"); } @After public void afterMethod() { System.out.println("after method"); } }

Execution from command prompt

java -cp junit-4.10.jar;test\TestCaseA.class; org.junit.runner.JUnitCore test.TestCaseA




Regards,
SantoshSarma J V




Friday, February 15, 2013

How to get auto populated Google search result?


Getting auto populated Google search result



Using below logic you can get the auto populated search result (Google search) for your search word

Logic
driver.get("http://www.google.co.in");  
 driver.findElement(By.name("q")).sendKeys("Test");  
 List<WebElement> autoPopulatedList=driver.findElements(By.cssSelector("tr>td>span"));  
 for(WebElement ele:autoPopulatedList)  
 {  
    System.out.println(e.getText());  
 }  



Example



Output of given code for above search word is 
selenium rc sendkeys
selenium puthon by
selenium
selenium tutorial
selenium  ide
selenium webdriver
selenium rc
selenium ide download
selenium grid
selenium documentation


Regards,
SantoshSarma

Passing parameters to TestCase using testng

Passing parameter using TestNg

  • Some times there is a need to send parameters (like browser name, browser version ..etc).
  • May be you want to run the same test case with different values for same attribute.
You can achieve above cases by using @parameter annotation in testng

Below is the example for running same test cases in different browsers (firefox, chrome) by passing different parameters (browser name, version, profile)

TestNg Class
import org.openqa.selenium.WebDriver;  
   import org.testng.annotations.Parameters;  
   import org.testng.annotations.Test;  
   import org.testng.annotations.BeforeMethod;  
   import org.testng.annotations.AfterMethod;  
   import org.testng.annotations.BeforeClass;  
   import org.testng.annotations.AfterClass;  
   import org.testng.annotations.BeforeTest;  
   import org.testng.annotations.AfterTest;  
   public class ExampleTestCase   
   {  
     private static WebDriver driver;
     @Parameters({"browser,version"})
     @BeforeClass
     public void beforeClass(String browser,String version,String profile)
     {
          driver=getDriverInstance(browser,version,profile);
     }
     @BeforeTest
     public void beforeTest()
     {
     }  
     @Test
     public void f()
     {
          //your test code here
     }
   @AfterTest
    public void afterTest()
    {
    }
    @AfterClass
    public void afterClass()
    {
        driver.quit();
    }
}

getDriverInstance method implimentation
public static WebDriver getDriverInstance(String browser,String version,String profile)  
  {  
     WebDriver driver=null;  
     if(browser.equals("firefox"))  
     {  
       DesiredCapabilities capability = DesiredCapabilities.firefox();  
       capability.setVersion(version);
       capability.setCapability(FirefoxDriver.PROFILE, profile);
       driver = new FirefoxDriver(capability);  
     }  
     else if(browser.equals("chrome"))  
     {  
         DesiredCapabilities capability = DesiredCapabilities.chrome();  
         capability.setVersion(version);  
         driver = new ChromeDriver(capability);  
     }  
     return driver;  
  }  

TestNg Suite
<?xml version="1.0" encoding="UTF-8"?>  
   <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
   <suite thread-count="2" name=MyTestSuite" parallel="tests">  
       <test name="RunInFirefox" preserve-order="false">
          <parameter name="browser" value="firefox">
          <parameter name="version" value="8"/>
          <parameter name="profile" value="default">
                <classes preserve-order="true">  
                      <class name="com.test.TestCase1"/>  
                      <class name="com.test.TestCase2"/>  
                      <class name="com.test.TestCase3"/>  
                </classes>  
       </test>  
       <test name="RunInChrome" preserve-order="false">
          <parameter name="browser" value="chrome">
          <parameter name="version" value="21"/>  
               <classes preserve-order="true">  
                    <class name="com.test.TestCase1"/>  
                    <class name="com.test.TestCase2"/>  
                    <class name="com.test.TestCase3"/>  
               </classes>  
        </test>  
</suite>  



Related Topics
Running Junit Cases from command prompt
Upload photo in facebook using webdriver

Friday, February 1, 2013

Uploading photo in facebook using WebDriver

Automate Facebook with WebDriver
Uploading photo in facebook

driver.get("http://www.facebook.com");  
  driver.findElement(By.id("email")).clear();  
  driver.findElement(By.id("email")).sendKeys("*******@gmail.com");  
  driver.findElement(By.id("pass")).clear();  
  driver.findElement(By.id("pass")).sendKeys("*******");  
  driver.findElement(By.cssSelector("#loginbutton > input")).click();  
  driver.findElement(By.linkText("Facebook")).click();  
  driver.findElement(By.linkText("Add Photos/Video")).click();  
  driver.findElement(By.xpath("//div[text()='Upload Photos/Video']/
                           following-sibling::div/input")).sendKeys("C:\\MyPhoto.jpg");  

Tuesday, January 29, 2013

WebDriver waits


Web application automation is depends on so many factors. Browser, network speed ...etc. We should write unquie code for running in all environments. For achieveing that we need to wait for WebElements before performing any operation on that.

Here we will see some built-in waits in WebDriver.

implicitlyWait

1WebDriver driver = new FirefoxDriver();
2driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
3driver.get("http://www.google.co.in");
4WebElement myElement = driver.findElement(By.id("someId"));
Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. (Click here for more information). This will be useful when certain elements on the webpage will not be available immediately and needs some time to load.

pageLoadTimeout

1driver.manage().timeouts().pageLoadTimeout(30, SECONDS);
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

setScriptTimeout

1driver.manage().timeouts().setScriptTimeout(30,SECONDS);

Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error.


Regards,
SantoshSarma