javaselenium-webdriverassertwebdriverwait

Using selenium assert with wait


I'm trying to use asserts in selenium java. I read that for every validation, I need to use an assert as best practice.
I stumbled upon this code example:

WebElement button = wait.until(ExpectedConditions.visibilityOf(signInAndUpBtn));
Assert.assertTrue(button.isDisplayed(), "Sign In button should be visible on Home Page");

In this example, the assertion will never fail because it will fail previously on the wait. However, I want to combine the use of wait and assert, but I'm not sure what's the best way to do it.


Solution

  • The assertTrue() after a wait.until() will never run if the element is not found or not visible. That’s because wait.until(...) throws a TimeoutException when the condition is not met within the given time. So the assertion becomes redundant.

    But you can control the assertion output - for example, to show a clean test failure message instead of a raw timeout exception, you can catch the TimeoutException and explicitly fail the test with your own assertion message.

    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    try { 
        wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
    } catch (TimeoutException e) {
        Assert.fail(message + " (Element not visible after " + timeoutSeconds + "s)");
    }
    

    hope this is help :)