zoukankan      html  css  js  c++  java
  • [selenium webdriver Java]使用自定义条件同步测试

    Selenium WebDriver可以结合ExpectedCondition类来定义自己期望的条件

    创建一个新的ExpectedCondition接口,必须实现apply方法

    等待元素出现

     1 public void testWithImplicitWait(){
     2     System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
     3     WebDriver driver = new ChromeDriver();
     4     driver.get("http://map.baidu.com");
     5 
     6         //点击展开当前城市
     7         WebElement curCity = driver.findElement(By.id("curCity"));
     8     curCity.click();
     9 
    10         //设置等待时间10秒
    11     WebDriverWait wait = new WebDriverWait(driver,10);
    12     //创建一个新的ExpecctedCondition接口,就必须实现apply方法
    13     WebElement message = wait.until(
    14             new ExpectedCondition<WebElement>(){
    15                 public WebElement apply(WebDriver d){
    16                     return d.findElement(By.id("selCityHotCityId"));
    17                 }
    18             }
    19             );
    20 
    21         driver.quit();
    22     }    
    示例代码

    等待元素属性值改变

    基于某些事件的操作后,元素的属性值可能会改变。例如,一个不可输入的文本框变为可输入状态。自定义的等待可以在元素的属性上实现。

    在这个例子中,ExpectedCondition类将等待返回Boolean值

    1 (new WebDriverWait(driver, 10).util(new ExpectedCondition<Boolean>(){
    2     public Boolean apply(WebDriver d){
    3       return d.findElement(By.id("username")).
    4 getAttribute("readonly").contains("true");  
    5     }
    6 }));

    等待元素变为可见

    开发人员会隐藏或是在一系列操作后显示某元素。指定的元素一开始已经存在于DOM中,但是为隐藏状态,当用户经过指定的操作后变为可见。那么这样的自定义期望条件应该如下:

    1 (new WebDriverWait(driver, 10).util(new ExpectedCondition<Boolean>(){
    2     public Boolean apply(WebDriver d){
    3       return d.findElement(By.id("xxx")).isDisplayed();  
    4     }
    5 }));

     等待DOM事件

    自定义的等待可以通过执行一段javascript代码并检查返回值来完成

    1 (new WebDriverWait(driver,10)).until(new ExpectedCondition<Boolean>(){
    2 public Boolean apply(WebDriver d){
    3 JavascriptExecutor js = (JavascriptExecutor) d;
    4 return (Boolean)js.executeScript("return jQuery.active == 0");
    5 }
    6 });
  • 相关阅读:
    Codeforces 631D Messenger KMP
    Google Codejam 2016 Round1A Problem C BFFs 简单图论
    ACM常用数论知识 总结
    C++ 虚函数表
    HDU 5661 Claris and XOR 贪心
    2013亚洲区域赛长沙站 ZOJ 3732 Graph Reconstruction
    [C++] upper_bound和lower_bound
    2015合肥网络赛 HDU 5489 Removed Interval LIS+线段树(树状数组)
    hdu 3532 Max Angle(atan2的使用)
    poj 1106 Transmitters (计算几何,叉积||极角排序)
  • 原文地址:https://www.cnblogs.com/missPersist/p/4204381.html
Copyright © 2011-2022 走看看