Home > Software design >  How to validate row numbers on webtable using selenium java?
How to validate row numbers on webtable using selenium java?

Time:01-23

Row starts with 0 and ends with 9.

I tried like this:

int counter = 0; 
for (int i = 0; i < 9; i  ) { 
    WebElement element = driver.findElement(By.xpath("//div[@class='hour ng-star']//span[text()='" i "']");
    if (element.isDisplayed()) {
        int value = Integer.parseInt(element.getText());
        if (value == counter) {
            counter  ; 
        } else {
            System.out.println("The row does not contain the expected values");
            break;
        }
    }

I need to add else part for if (element.isDisplayed()) { block, where should I include else part of first if statement?

CodePudding user response:

You need to add else block for if (element.isDisplayed()) after the if() completes, i.e.

int counter = 0; 
for (int i = 0; i < 9; i  ) { 
    WebElement element = driver.findElement(By.xpath("//div[@class='hour ng-star']//span[text()='" i "']");
    if (element.isDisplayed()) {
        int value = Integer.parseInt(element.getText());
        if (value == counter) {
            counter  ; 
        } else {
            System.out.println("The row does not contain the expected values");
            break;
        }
    } else {
    
        // else part of element.isDisplayed()
    }

CodePudding user response:

To answer your question, the else part of the if goes right after the closing } of the if statement, just as you did with the inner if, e.g.

int counter = 0; 
for (int i = 0; i < 9; i  ) { 
    WebElement element = driver.findElement(By.xpath("//div[@class='hour ng-star']//span[text()='" i "']"));
    if (element.isDisplayed()) {
        int value = Integer.parseInt(element.getText());
        if (value == counter) {
            counter  ; 
        } else {
            System.out.println("The row does not contain the expected values");
            break;
        }
    } else {
       // else of if (element.isDisplayed()) 
    }
}

Having said that, I noticed a bug and wanted to give other feedback to simplify your code.

  1. In your question you indicated that the columns are numbered 0-9 but your if only goes from 0-8,

    for (int i = 0; i < 9; i  )
    

    but it should be

    for (int i = 0; i <= 9; i  )
                       ^ note the added equals sign
    
  2. By putting the i value in the XPath, ...//span[text()='" i "'], you've already verified the text contained in the element so there's no need to parseInt and compare the values. Your entire code snippet can be reduced to

    for (int i = 0; i <= 9; i  ) {
        WebElement element = driver.findElement(By.xpath("//div[@class='hour ng-star']//span[text()='"   i   "']"));
    }
    

    This code will throw an NoSuchElementException if one of the elements is not present, i.e. the text is not there or in the correct order.

  • Related