Home > Software engineering >  after deleting an item and check if the item was successfully deleted and print the information only
after deleting an item and check if the item was successfully deleted and print the information only

Time:10-29

List<WebElement> list= driver.findElements(By.xpath("Abc"));
        for (int i = 0; i< list; i  ) {
            if (list.get(i).getText().equals("Newly Created From Automation")) {
                logger.info("Unable to delete Saved Filter Successfully");
            }
            else {
                logger.info("Filter deleted successfully");
            }
         }

I want the if condition to check for all elements and print else condition only once, if the if condition is false for all elements, but instead it keeps on printing the code in else for every webElement.

CodePudding user response:

In order to get what you are looking for you should change the logics of your code.
One of the possible ways to do it can be as following:

  1. Collect al the elements texts into a list.
  2. iterate over the texts. In case the desired text is found - print the corresponding output. If that text was not found - print the other output.
    See the code example below
List<WebElement> list = driver.findElements(By.xpath("Abc"));
List<String> texts = new ArrayList<>();
for(WebElement element : list){
    texts.put(element.getText());
}
boolean found = false;
for(String str: texts) {
if(str.trim().contains("Newly Created From Automation")){
    logger.info("Unable to delete Saved Filter Successfully");
    found = true;
}
if(!found){
    logger.info("Filter deleted successfully");
}

CodePudding user response:

Use Stream API allMatch to check if all the web element texts have the value "Newly Created From Automation" and if it is true print the message "Filter deleted successfully" else print "Unable to delete Saved Filter Successfully":

boolean filterDeleted = list.stream().allMatch(webElement -> 
    webElement.getText().equals("Newly Created From Automation"));

    if(filterDeleted)){
        logger.info("Filter deleted successfully"); 
    }else{
        logger.info("Unable to delete Saved Filter Successfully");
    }

CodePudding user response:

You can simply use a for each loop like this :

List<WebElement> list = driver.findElements(By.xpath("Abc"));
for(WebElement element : list) {
    if(element.getText().equals("Newly Created From Automation")) {
        System.out.println("WebElement text matched with Newly Created From Automatio");
        logger.info("Unable to delete Saved Filter Successfully");
    }
    else {
        System.out.println("For WebElement"   element.getAttribute("innerHTML")   " seems like it does not have Newly Created From Automation");
        logger.info("Filter deleted successfully");
    }
}

It quite equivalent to what you already have,

but your for loop should be like this :

for (int i = 0; i< list.size(); i  ) {

not

for (int i = 0; i< list; i  ) {
  • Related