【问题标题】:Selenium -- wait for eventSelenium——等待事件
【发布时间】:2012-09-18 11:39:50
【问题描述】:

我需要创建一个测试用例,它会有一个 facebook 登录。 那么如何强制测试用户使用 facebook 登录以继续测试?

这是我想要的程序:

  1. 用户点击链接,

  2. 它重定向到 facebook 登录,

  3. 检查页面内容。

【问题讨论】:

  • 您自己尝试过任何代码吗?如果有,请发帖。

标签: unit-testing testing selenium


【解决方案1】:

使用以下方法。 1) 找到你要点击的链接的css选择器。

String cssSelector = ..blablalba..;

//现在您可以点击找到的链接了

driver.findElement(By.cssSelector(cssSelector)).click();

//或直接使用js:

JavascriptExecutor js = (JavascriptExecutor) driver;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("var x = $(\'"+cssSelector+"\');");
        stringBuilder.append("x.click();");
        js.executeScript(stringBuilder.toString());

2) 要验证页面的内容,您可以在 fb 页面上找到几个 web 元素,并简单地验证页面上存在该元素:

input.findElements(By.xpath("//xpath")).size() > 0
//or by css selector: 
input.findElements(By.cssSeector("html>...blablabla...")).size() > 0
driver.findElement(By.cssSelector("html>...blablabla...")).isDisplayed()

或者只是使用流畅的等待等待 fb 登录页面上出现基本元素:

 public WebElement fluentWait(final By locator){
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);

        WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                        return driver.findElement(locator);
                }
                }
);
                           return  foo;              }     ;

希望对你有帮助)

【讨论】:

    【解决方案2】:

    你也可以用这个方法:

    new WebDriverWait(driver, 60).until(ExpectedConditions.presenceOfElementLocated(By.id("save")));
    

    //您的网络对象 ID 是“保存”。

    或者,您可以使用自定义方法。请参阅下面的示例方法,

     public static boolean waitForElement(By element, int timeOutInSeconds){
        boolean found = false;
        try{
            int counter=1;
            while(counter<timeOutInSeconds){
                if(driver.findElements(element).size()>0){
                    found = true;
                    break;
                }
                else{
                    Thread.sleep(1000);
                    counter++;
                }
            }
            return found;
        }
        catch(Exception e){
            e.printStackTrace();
            return found;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多