I have written the following code for looping through WebElements in Selenium.
Can someone please provide me with feedback on how to improve my code?
public static void checkAbsentSearchResult(String title, String Testgoal) throws IOException{
try{
List<WebElement> allSearchResults = driver
.findElements(By
.xpath("//*[contains(@class, 'teaser-list')]/li/article/div[2]/h3"));
//Check if xpath contains any WebElements, if not check if no results message is displayed
if(allSearchResults == null || allSearchResults.size() < 1 ){
String element = driver.findElement(By.xpath("//div[@class='view-empty']")).getText();
if(element.contains("no results found")){
WriteToXSL.WriteTo(Testgoal, "OK", "");
WriteToPDF.addRow(Testgoal, "OK", "");
}else{
WriteToXSL.WriteTo(Testgoal, "NOK", element.toString());
WriteToPDF.addRow(Testgoal, "NOK", "");
}
}else{
boolean resultsFound = false;
for (WebElement Element : allSearchResults) {
if (Element.getText().contains(title)) {
WriteToXSL.WriteTo(Testgoal, "NOK", "");
WriteToPDF.addRow(Testgoal, "NOK", "");
resultsFound = true;
break;
}// close if
}// close for loop
if (resultsFound == false) {
WriteToXSL.WriteTo(Testgoal, "OK", "");
WriteToPDF.addRow(Testgoal, "OK", "");
}
}
}catch(Exception e){
WriteToXSL.WriteTo(Testgoal, "NOK", e.toString());
WriteToPDF.addRow(Testgoal, "NOK", "");
}
}