Gbru
Gbru

Reputation: 1087

Do While Loop and ExpectedConditions - Possible to use together?

Do While Loop and ExpectedConditions - Possible to use together?

  1. Iam getting the odd unable to locate element / timeout exception with the method listed below.

2. Is it possible to add a while loop so the method can check and execute more than once?

    public void waitAndClickElement(WebElement element) throws InterruptedException {
    try {
        this.wait.until(ExpectedConditions.elementToBeClickable(element)).click();
        System.out.println("Successfully clicked on the WebElement: " + "<" + element.toString() + ">");
    }catch (Exception e) {
        System.out.println("Unable to wait and click on WebElement, Exception: " + e.getMessage());
        Assert.assertFalse(true, "Unable to wait and click on the WebElement, using locator: " + "<" + element.toString() + ">");
    }
}

Upvotes: 0

Views: 1076

Answers (1)

Cathal
Cathal

Reputation: 1338

Yes, thats possible. Something like this:

    boolean clicked = false;
    int attempts = 0;
    while(!clicked && attempts < 5) {
    try {
            this.wait.until(ExpectedConditions.elementToBeClickable(element)).click();
            System.out.println("Successfully clicked on the WebElement: " + "<" + element.toString() + ">");
            clicked = true;
     } catch (Exception e) {
            System.out.println("Unable to wait and click on WebElement, Exception: " + e.getMessage());
            Assert.assertFalse(true, "Unable to wait and click on the WebElement, using locator: " + "<" + element.toString() + ">");
        }
         attempts++;
    }

It might be a good idea to add a max attempts to your while loop too, so you dont get caught in an infinite loop.

Upvotes: 1

Related Questions