Skip to content

Instantly share code, notes, and snippets.

@cliffdarling
Created March 21, 2012 14:42
Show Gist options
  • Save cliffdarling/2147664 to your computer and use it in GitHub Desktop.
Save cliffdarling/2147664 to your computer and use it in GitHub Desktop.
Selenium Web Driver condition used to wait until some specific or non-empty text Is present in an element
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
/**
* Implementation of ExpectedCondition that waits until some specific text is present
* in the specified element
* If the expected text is null, this will wait until there is any non-empty text in the element.
* If expected text is not null, this will wait until the text of the element exactly matches the expected text
* @author cliff.darling
*
*/
public class ExpectedTextIsPresent implements ExpectedCondition<Boolean> {
private By locator;
private String expectedText;
/**
* @param locator the locator to find the element where the expected text will be compared to
* @param expectedText the text to wait for. If null, will wait for any non-empty text
*/
public ExpectedTextIsPresent (By locator, String expectedText){
this.locator = locator;
this.expectedText = expectedText;
}
/**
* {@inheritDoc}
* @see com.google.common.base.Function#apply(java.lang.Object)
*/
public Boolean apply(WebDriver input) {
try {
String elementText = input.findElement(locator).getText();
return elementText!=null &&
(!"".equals(elementText.trim()) || expectedText.equals(elementText.trim()));
} catch (StaleElementReferenceException e) {
return null;
}
}
}
@fpedroza
Copy link

fpedroza commented Jul 8, 2021

Can't expectedText be null here then?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment