让wait函数在失败时执行某些操作



我是Selenium和Java编写测试的初学者。我知道我可以使用下面的代码尝试点击一个网络元素两次(或我想要的次数):

for(int i=0;i<2;i++){
    try{
             wait.until(wait.until(ExpectedConditions.visibilityOfElementLocated
                  (By.xpath("//button[text()='bla bla ..']"))).click();
              break;
       }catch(Exception e){ }
 }

但我想知道是否有什么东西可以像把一个veriable传递给等待函数,让它自己做第i次,比如:

wait.until(wait.until(ExpectedConditions.visibilityOfElementLocated
                      (By.xpath("//button[text()='bla bla ..']"),2)).click();

例如,这里的2可能意味着,如果失败了,试着做两次,我们有这样的事情吗?

看看FluentWait,我认为这将涵盖您指定适当超时和轮询间隔的用例。https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

如果在ExpectedConditions集合中找不到满足您需要的东西,您可以随时编写自己的。

WebDriverWait.tille方法可以传递给com.google.common.base.Function.com.google.common.base.Fpredicate。如果您创建自己的Function实现,那么值得注意的是,任何非null值都将结束等待条件。对于谓词,apply方法只需要返回true。

有了这一点,我相信你对这个API几乎没有什么不能做的。你所询问的功能可能并不开箱即用,但你有完全的能力创建它

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Predicate.html

祝你好运。


未测试的代码段

final By locator = By.xpath("");
      Predicate<WebDriver> loopTest = new Predicate<WebDriver>(){
        @Override
        public boolean apply(WebDriver t) {
            int tryCount = 0;
            WebElement element = null;
            while (tryCount < 2) {
                tryCount++;
                try {
                    element = ExpectedConditions.visibilityOfElementLocated(locator).apply(t);
                    //If we get this far then the element resolved.  Break loop.
                    break;
                } catch (org.openqa.selenium.TimeoutException timeout) {
                    //FIXME LOG IT
                }
            }
            return element != null;
        }
      };
      WebDriverWait wait;
      wait.until(loopTest);

最新更新