WebDriver wait.until using the arrow function throws exception when false



  • This works if true but fails when it hits false. Is there any way to make this work while it is true?

            WebDriverWait wait = new WebDriverWait(driver, 30);
            ExpectedCondition<Boolean> colorIsInThreshold = arg0 -> {
                try {
                    if(isTrue){
                        Assert.assertTrue(colorPixel > threshold);
                        return true;
                    }else{
                        Assert.assertTrue(colorPixel < threshold);
                        return true;
                    }
                } catch (Exception e) {
                    return false;
                }
            };
            wait.until(colorIsInThreshold);
    


  • I tried your code:

    so if you read the documentation of asserttrue:

    https://www.javadoc.io/doc/org.testng/testng/6.8.17/org/testng/Assert.html#assertEquals(boolean,%20boolean,%20java.lang.String)

    you can see that asserttrue throws an error and not an exception.

    In java, Exception and Error are subclasses of the parent class called Throwable.

    https://www.geeksforgeeks.org/exceptions-in-java/

    So in your code you are trying to catch an exception, and thus your code never reaches the catch block. So instead, replace exception with throwable :

     WebDriverWait wait = new WebDriverWait(driver, 30);
            ExpectedCondition<Boolean> colorIsInThreshold = arg0 -> {
                try {
                    if(isTrue){
                        Assert.assertTrue(colorPixel > threshold);
                        return true;
                    }else{
                        Assert.assertTrue(colorPixel < threshold);
                        return true;
                    }
                } catch (Throwable e) {
                    return false;
                }
            };
            wait.until(colorIsInThreshold);
    

    Tips:

    if you are returning true or false, then why are you asserting it? use below code and you will get what you need.

            WebDriverWait wait = new WebDriverWait(driver, 30);
            ExpectedCondition<Boolean> colorIsInThreshold = arg0 -> {
                   return isTrue ? colorPixel > threshold : colorPixel < threshold;
            };
            wait.until(colorIsInThreshold);
    

    Also , what should be the behavior when pixel is equal to threshold?



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2