Category Menu

Categories

Interview Questions Category Menu

Interview Questions

Cheat Sheet Category Menu

Cheat Sheets

How to validate a row in a table

Posted on

Most of the time when this question is been asked in the interview, candidates are less likely to give the best answer. Most common answer is using findElements and loop through the element list and validate each record. In this post let's see how to we can handle such scenario.
In the following table we have a list of record of a candidate. We need to validate if Candidate3 and its associate data is displayed in the table. Here we need to validate Candidate Name, Age, Location.
Candidate NameAgeLocation
Candidate126New York
Candidate230Mumbai
Candidate326Bengaluru
Candidate428Washington
You don't need to create any loop here instead you can use xpath to validate the record. This will reduce the code and can be handled in a single line of code.
For this validation we can use relative XPath as follows.
XPATH : //table/tbody/tr[td[text()='Candidate3'] and td[text()='26'] and td[text()='Bengaluru']]
Rather than using a findElements and creating a for loop and validating each td elements from it, we can write a single findElement using XPath and can validate in one line of code. Let's see when we put everything together in the code.
Java
Copy
WebDriver wd = new ChromeDriver();
wd.get("https://www.testautomationstudio.com/blog/posts/how-to-validate-a-row-in-a-table/");
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
assertTrue(wd.findElement(By.xpath("//table/tbody/tr[td[text()='Candidate3'] and td[text()='26'] and td[text()='Bengaluru']]")).isDisplayed(), true)
Even though the order of the column changes in the above table, your code will still work. This way we can use XPath to validate multiple data at once.