Skip to content

How can we pass in an ExpectedConditions as a parameter to wait.until in Selenium Java?

I’m finding trouble passing in an ExpectedConditions as a parameter in a method to wait.until(). The wait.until() expects a function to be passed in. I am relatively new to Java, and would appreciate the assistance.

Offending code:

public void waitUntil(WebElement element, long seconds, String errorMessage, ExpectedConditions expectedConditions) {
 if (seconds == 0 || errorMessage.isEmpty()) throw new IllegalArgumentException();
 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(seconds));
 wait.withMessage(errorMessage);
 // this throws a compiler error.
 wait.until(expectedConditions);
}

wait.until() expects a function to be passed into it, which looks like ExpectedConditions.urlToBe("http://www.test.com").

I am trying to make a method that could be called where any ExpectedCondition i.e. urlToBe, alertIsPresent etc.. could be passed in.

Thank you.

Answer

(WebElement element, long seconds, String errorMessage, ExpectedConditions expectedConditions)

In first place, the type of expectedConditions is wrong.

You declared it as ExpectedConditions, which represents the util class.

You actually want ExpectedCondition, the type which all methods from ExpectedConditions returns.

But just changing it to ExpectedCondition is not enough. Because you will receive an warning about Raw type, because ExpectedCondition is a generic class.

So you have to declare the type parameter of class, and because you want to include everything, you use wildcard ?

In the final, the parameter should be ExpectedCondition<?> expectedConditions