Friday, October 26, 2012

Synchronization or Waits in Selenium WebDriver


When our automation execution starts, then there should be fair communication between tool and application.
What i mean here is if the tool is too fast of execution and the application/objects are not fully loaded/not ready by that time, then our automation test cases will fail. So the tool should wait(appropriate) till the objects are present/ready in the application, so that communication/synchronization happens between the tool and application so the chances of our test cases will pass.

Synchronization or Waits can be done in two ways.
1. Explicit Waits
2. Implicit Waits

Explicit Waits:
This can be achieved in 2 ways.

Thread.sleep:
Thread.sleep waits the specified time irrespective of the object state.
Ex: Thread.sleep(30000);
Here the execution is halted for 30 Sec., even if the object you are looking exists in 10 sec. So here tool unnecessarily waits for 20 sec.
Execution wont wait after 30 sec.s even if the object does not available, so the chances of your Test fails.

WebDriverWait:
We can tell the tool to wait only till the Condition met. Once the condition is met, the tool proceed with the next step.
This can be done with WebDriverWait in conjunction with ExpectedConditions Class.
There are few methods supported in ExpectedConditions class to support synchronisation.
Here is the example:
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement o_element = wait.until(ExpectedConditions.elementToBeClickable(By.id("Object Id")));

Here the tool waits a maximum time of 30 Sec., if the object you are looking is displayed in 10 sec. then the execution proceeds with the next step afte 10 secs. rather than waiting for 30 secs.

If you dont want to include any methods in ExpectedConditions class, then you can use below code:
WebDriver driver = new FirefoxDriver();
driver.get("Your URL");
WebElement o_Element = (new WebDriverWait(driver, 30))
  .until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
        return d.findElement(By.id("Object Id"));
    }});
Here WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully or wait for maximum of 30 sec.


Implicit Waits:
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("Your URL");
WebElement o_Element = driver.findElement(By.id("Object Id"));

How to retrieve web table content using Selenium WebDriver

There are many ways we can do this,
but in below example i am following "tr","td" approach.

WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://money.rediff.com/");
       
WebElement element=driver.findElement(By.id("allpage_links"));
List<WebElement> rowCollection=element.findElements(By.xpath("//*[@id='allpage_links']/tbody/tr"));


System.out.println("Numer of rows in this table: "+rowCollection.size());
//Here i_RowNum and i_ColNum, i am using to indicate Row and Column numbers. It may or may not be required in real-time Test Cases.      
int i_RowNum=1;
for(WebElement rowElement:rowCollection)
{
      List<WebElement> colCollection=rowElement.findElements(By.xpath("td"));
      int i_ColNum=1;
      for(WebElement colElement:colCollection)
      {
           System.out.println("Row "+i_RowNum+" Column "+i_ColNum+" Data "+colElement.getText());
           i_ColNum=i_ColNum+1;
       }
    i_RowNum=i_RowNum+1;
 }
 driver.close();


How to retrieve a specifec cell value from a web table using Selenium WebDriver

Here in this example i covering how to retrieve a specific cell value from Web Table using Selenium WebDriver:

The below code works well if the Cell contains plain text than any other controls etc.

int rownum,colnum;
String s_xpath;
       
WebDriver driver=new FirefoxDriver();
driver.get("https://www.irctc.co.in/");
       
rownum=2;
colnum=1;
//Here i am framing the xpath with rownum and colnum       
s_xpath="//*[@id='tabslinks']/tbody/tr["+rownum+"]/td["+colnum+"]";





//getText method retrieves the cell value.
System.out.println(driver.findElement(By.xpath(s_xpath)).getText());

Thursday, October 25, 2012

How to take a screenshot of the window using Selenium WebDriver

Below code demonstrate about how to take a snapshot of the Desktop window using Selenium WebDriver:


import java.io.File;
import java.io.IOException;
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 TakeAScreenShot
{
    public static void main(String[] args)
    {
        WebDriver driver = new FirefoxDriver();
        String s_FilePath="c:\\screenshot.jpg";
       
        driver.get("http://www.google.com/");
        try
        {
            File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            //Once we have the screenshot in our file 'srcFile' you can use all FileUtils methods like
            FileUtils.copyFile(srcFile, new File(s_FilePath));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}

How to select an item in Listbox using Selenium Webdriver





There are many ways you can do this.

Below are my best ways to select a list item from a listbox:

Option 1:
//First find the Listbox element as WebElement.
WebElement o_Item= driver.findElement(By.id("uw_flight_origin_input_d"));
//Then select the list item from the WebElement
o_Item.findElement(By.xpath("//option[contains(text(),'" + nameYouWant + "')]")).click();

Option 2:
Select menu = new Select(driver.findElement(By.id("uw_flight_origin_input_d"))); menu.selectByVisibleText(nameYouWant);

A complete sample code is here:
import org.openqa.selenium.support.ui.Select;
WebDriver driver=new FirefoxDriver();
driver.get("http://www.expedia.co.in/");
String nameYouWant="Hyderabad";
WebElement o_Item= driver.findElement(By.id("uw_flight_origin_input_d")); o_Item.findElement(By.xpath("//option[contains(text(),'" + nameYouWant + "')]")).click();
/*Select menu = new Select(driver.findElement(By.id("uw_flight_origin_input_d"))); menu.selectByVisibleText(nameYouWant);*/

In the same way how to select a checkbox or radio button based on a value:
Here is a sample HTML code  for an application
<html>
<head></head>
<body>
<form>
<Input type="radio" name="sex" value="male">Male<br>
<Input type="radio" name="sex" value="female">Female<br>
Likes          :<br>
<input type="checkbox" name="likes" value="cars">Cars<br>
<input type="checkbox" name="likes" value="bikes">Bikes<br>
<input type="checkbox" name="likes" value="Movies">Movies<br>
</form>
</body>
</html>

WebDriver driver=new FirefoxDriver();
driver.get("FilePath);
       
driver.findElement(By.xpath("//input[@name='sex' and @value='female']")).click();
       
driver.findElement(By.xpath("//input[@name='likes' and @value='Movies']")).click();