【问题标题】:If element visible do action and pass test, else only pass test如果元素可见执行操作并通过测试,否则仅通过测试
【发布时间】:2023-03-07 03:26:02
【问题描述】:

我想在元素显示时将数字保存到文件中,然后测试应该通过。 否则,如果元素不可见,也应通过测试,但不应将数字保存到文件中。

显示元素时保存数字可以正常工作,当元素不显示测试时也不要将其保存到文件中,这样也可以正常工作。

两个问题:

  1. Selenium 搜索元素时不显示大约... 15 秒?太长了,如何减少这个时间?使用等待?

  2. 最重要的是,如果元素不显示测试失败,我想通过它,因为整个过程已经完成,等待这个元素和保存数字是额外的事情。

public void saveNumberIntoFile(String fileNumber) throws IOException {

   if(messageInfo.isDisplayed())

{BufferedWriter writer = new BufferedWriter(
new FileWriter("C:\\Users\\xxx\\Documents\\samplefile.txt", true) //Set true for append mode
);
writer.newLine(); //Add new line
writer.write(fileNumber);

writer.close();}


}

【问题讨论】:

    标签: java selenium selenium-webdriver automated-tests


    【解决方案1】:

    您需要WebDriverWaitExpectedConditions 来处理等待元素,如下所示:

    new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.name("")));
    

    By.name("") 替换为您在messageInfo 上缩写的定位器。

    15 以秒为单位,如果元素被定位到它不会等到 15s。

    但是如果在某个时间段内我们已经确定没有找到该元素,则会返回错误:

    NoSuchElementException: Cannot locate an element using....
    

    您的测试将停止,因此您需要处理try/catch

    public void saveNumberIntoFile(String fileNumber) throws IOException {
        try {
            new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.name("")));
            BufferedWriter writer = new BufferedWriter(
            new FileWriter("C:\\Users\\xxx\\Documents\\samplefile.txt", true) //Set true for append mode
            );
            writer.newLine(); //Add new line
            writer.write(fileNumber);
    
            writer.close();
        } catch (NoSuchElementException e) {
            // TODO: handle exception
        }
    }
    

    【讨论】:

    • 我复制了你的解决方案,当元素显示正常时,当仍然没有测试失败原因:org.openqa.selenium.NoSuchElementException:没有这样的元素:无法找到元素:{“method”:“ css 选择器","selector":"*[name='//*[@id="ordersummary"]/div/div[3]/div[1]/div/div[1]/div']"}
    • 另外添加了超时异常,工作正常,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2021-12-13
    相关资源
    最近更新 更多