0

I have the below method in my code to check if a text was updated on the web page. As for the code, I will keep refreshing the web page until the text changes to "Hot" and call the same method again and again to check the XPath value.

public void waitTillStatuschange() {
  if(!driver.findElement(By.Xpath(Status)).contains("Hot")) {
      driver.refreshBrowser();
      waitTillStatuschange();
   }
}

I have sometimes seen the same piece of code executing for more than 3, or 4 hours as the text has not changed to "Hot".

So what might be the best option to forcefully end this method if the text did not change after refreshing for 4 times?

2 Answers 2

2

You can use a custom ExpectedConditions

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(MAX_TIME_I_WANT_TO_WAIT));    
wait.until(new TextIsVisibleWithRefresh(By.Xpath(Status), "Hot"));

public class TextIsVisibleWithRefresh implements ExpectedCondition {        
  String expectedText;
  String element;

  public TextIsVisibleWithRefresh(WebElement element, String expectedText) {
    this.element = element; 
    this.expectedText = expectedText;
  }
    
  @Override
  public Boolean apply(WebDriver driver) {      
    String text = this.element.getText();
    if(expectedText.equals(text)) {
       return true;
    }
    driver.refreshBrowser();
    return false;
  } 
}
1
0

There are multiple workarounds to handle such scenarios while doing web automation using Selenium. While working in software testing company and developing frameworks in multiple languages below are top 03 approaches widely used -

Method 1) Use Polling Wait - Major Benefit of using Polling wait is you can refresh application as per required frequency and also, can end the wait as per your threshold wait limit. High level code is -

    WebDriver driver = new ChromeDriver();
    WebElement element = driver.findElement(By.xpath("Status"));
    WebDriverWait wait = new WebDriverWait(driver, 40);
    wait.pollingEvery(2, TimeUnit.SECONDS);
    wait.until(ExpectedConditions.elementToBeClickable(element));
    element.click();

Method 2) Enclose your code inside a Loop. Use Counter and assign a threshold value. Increment count after each refresh and break once threshold is achieved.

Method 3) Create Dynamic Custom Expected Conditional Code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.