Wednesday, March 7, 2012

WebDriver - Dynamic Table

Scenario: Sometimes we have a dynamic table, in which neither the number of rows, or the order is constant. And in such case if you have to verify and particular values from the table you can use the following technique.

Assumption: Following table is dynamic table, which can have any number of rows and order or the records may also change every time you load.

Names Designationsalary
GaurangConfused45000
AjayTeam Lead50000
BinoyQA40000
SantoshProject Manager100000

TestCase: Verify the Salary of Gaurang from the above table.

/**
 * @author Gaurang Shah
 * Purpose: To demonstrate how to verify Dynamic Table in Selenium 
 */
import static org.junit.Assert.*;

import java.util.List;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WebDriverTable {
 public static WebDriver driver;

 @BeforeClass
 public static void setup() {
  // Create a new instance of the Firefox driver
  driver = new FirefoxDriver();
  driver.get("http://qtp-help.blogspot.in/2012/02/selenium-verify-table.html");
 }

 @AfterClass
 public static void tearDown() {
  // Close the browser
  driver.quit();
 }

 @Test
 public void testDynamicTable() throws InterruptedException {

  String salary = "0";
  List<WebElement> totalRows = driver.findElements(By
    .xpath("//table[@name='salaryTable']/tbody/tr"));

  for (int row = 1; row <= totalRows.size(); row++) {
   // Fetch the text of first column (name)
   String name = driver.findElement(By.xpath("//table[@name='salaryTable']/tbody/tr["+row+"]/td[1]")).getText();

   // If name matches gaurang fetch the text of third column (salary)
   if (name.equalsIgnoreCase("gaurang")) {
    salary = driver.findElement(By.xpath("//table[@name='salaryTable']/tbody/tr["+row+"]/td[3]")).getText();
   }
  }

  System.out.println(salary);
  assertEquals("Verify Salary", "45000", salary);
 }
}


2 comments:

Unknown said...

Thanks man that's perfectly helpful,I hope you will post more too.

Unknown said...

Thanks..:)I have to automate for a chat application using webdriver. Please an you help me out in doing this.

Post a Comment