Friday, February 24, 2012

Selenium - Verify 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 org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import static org.junit.Assert.*;
public class SeleniumTable {
 public static Selenium selenium;
 @BeforeClass
 public static void setUp() throws Exception {
  selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://qtp-help.blogspot.in");
  selenium.start();
  selenium.windowMaximize();
 }
 
 @Test
 public void ItrateTable(){
  int salary = 0;
  selenium.open("/2012/02/selenium-verify-table.html");
  
  //Find out how many rows this table has.
  int totalRows=selenium.getXpathCount("//table[@name='salaryTable']/tbody/tr").intValue();
  
  for(int row=1; row<=totalRows; row++){
   //Find the row whose first column has name as Gaurang
   String name = selenium.getText("//table[@name='salaryTable']/tbody/tr["+row+"]/td[1]");
   if(name.equalsIgnoreCase("gaurang")){
    //When you find row get the value of third column of that table.
    salary = Integer.valueOf(selenium.getText("//table[@name='salaryTable']/tbody/tr["+row+"]/td[3]"));
   }
  }
  System.out.println("salary="+salary);
  assertEquals("Verify Salary", 45000,salary);
 }
 
 @AfterClass
 public static void tearDown() throws Exception {
  selenium.stop();
 }
}