Home > Software engineering >  Selenium - why override 'apply' in custom Expected Conditions?
Selenium - why override 'apply' in custom Expected Conditions?

Time:12-29

I can't find the answer and I'd like to understand why we do it this way, so: why, when creating custom ExpectedConditions, we have to override the apply method? It's most probably something simple and basic, but I just can't get it.

here's an example that I found online:

public boolean customExpectedConditions() {

    WebDriverWait wait = new WebDriverWait(driver, 60);

    ExpectedCondition<Boolean> jqLoaded = new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) { // why this part?
        try {
          return ((Long)((JavascriptExecutor)getDriver()).executeScript("return jQuery.active") == 0);
        }
        catch (Exception e) {
          // no jQuery present
          return true;
        }
      }
    };

  return wait.until(jqLoaded);
}

CodePudding user response:

You need to override that because Wait implementations in Selenium (like FluentWait) expects implementation of Function interface to test the condition.

ExpectedCondition<Boolean> just extends that interface to restrict what goes to your "function" as a parameter. It restricts it to WebDriver objects.

So when you prepare your own condition you need to implement logic that would tell to Selenium that the condition is either met or not. You do that by overriding apply method.

You can find some more details of how waiters in Selenium work with conditions in the case of FluentWait (other waiters work in the exactly same way).

You can also check this to find some more examples of custom conditions in Selenium and see that they are flexible enough to work for any sort of event you can detect with Java.

  • Related