Search code examples
javaseleniumassert

Selenium (Java): Do both positive AND negative check whether page is loaded correctly


In Selenium, there are standard checks whether a page has been loaded technically correct. For example:

@FindBy(id = "loginButton")
private WebElement loginButton;

@Override
public void assertLoadedTechnicallyCorrect() {
    WebDriverWait wait = waitWithTimeoutSeconds(10);
    wait.until(ExpectedConditions.elementToBeClickable(loginButton));
}

The problem: Often you don't have to wait 10 seconds if the page is loaded or not, as a different page with an error message (let's call it alertMessage) is loaded much faster. In this case, no login button will be on the page.

So expected behavior is:

  • Wait until either loginButton or alertMessage is clickable (of course, displayed would be enough for the alertMessage, but it's also clickable).
  • If it was loginButton, go on with the test case.
  • If it was alertMessage, stop and throw an error message.

A similar question has been posed and answered under Selenium Expected Conditions - possible to use 'or'?

However, the solution suggested there by artfulrobot with defining an "AnyEc" class does not work in the same way, as I need opposite behavior for the different cases - not the same behavior.


Solution

  • There are several ways to resolve this.

    If that is the case you can use.

    driverWait.until(ExpectedConditions.or(
        ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.something")),
        ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.anything"))));
    

    and then check separately which element is displayed like

    if(driver.findelements(By.xpath("loginbutton")).size>0) 
    //do loginbutton code part
    
    else if (driver.findelements(By.xpath("error message")).size>0)
     //do error part