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.
TestCase: Verify the Salary of Gaurang from the above table.
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 | Designation | salary |
Gaurang | Confused | 45000 |
Ajay | Team Lead | 50000 |
Binoy | QA | 40000 |
Santosh | Project Manager | 100000 |
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); } }