gpt4 book ai didi

java - Selenium 测试运行速度太快,没有等待单选按钮被选中

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:42 25 4
gpt4 key购买 nike

我有一个运行速度过快的 Selenium Grid 和 WebDriver 2.48.2 测试。大多数情况下测试停止是因为在按下按钮之前没有选择单选按钮。

单选按钮是使用基于 JSON 文件的 JavaScript 设置的,可以在一个部分中动态创建任意数量的单选按钮。单击继续按钮后,该部分将被销毁,并创建一个带有新单选按钮的新部分。

我尝试了隐式等待但没有成功。

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

唯一对我有用的解决方案是延迟,以便有足够的时间单击单选按钮。

driver.findElement(By.id("radiobuttonid")).click();
Thread.sleep(delay);

但在我看来这不是一个理想的解决方案,有可能延迟不够长或者延迟太长,浪费时间;可以有任意数量的单选按钮,因此时间将呈指数增长。

我试过设置各种 explicit waits与不同expected conditions但没有成功。

我已经尝试等待创建单选按钮,因为它可能不存在(presenceOfElementLocated & elementToBeClickable)。我试过等待它被选中 (elementToBeSelected)。

我很难准确地找到预期条件应该做什么,因为描述很简短并且容易引起误解。

理想情况下,我希望测试在单击单选按钮后立即继续。如果可能,最好的方法是什么?

编辑

L.Bar 的 suggestion下面对我不起作用,但确定单选按钮存在非常有帮助,只是在单选按钮有机会被选中之前单击继续按钮。

编辑 2

这只是为了扩展 Jeremiah 的正确答案。我将代码放入一个方法中以使其可重用。

private static Predicate<WebDriver> forceSelectionOfElement (final String id)
{
return new Predicate<WebDriver>()
{
@Override
public boolean apply(WebDriver arg0)
{
WebElement element = arg0.findElement(By.id(id));
boolean rval = element.isSelected();

if (!rval) {
element.click();
}

return rval;
}
};
}

用法

WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(forceSelectionOfElement("q___01_02_01___1___a"));

记得导入这个命名空间,我花了很长时间才发现我导入错了:)

import com.google.common.base.Predicate;

最佳答案

我遇到过类似的问题,但就我而言,我的“点击”事件在某处丢失了。我的测试会继续,点击代码会触发,但元素的状态永远不会明显改变,测试会失败。我最终通过添加一个自定义谓词来利用 WebDriverWait 的循环行为,该谓词对所选状态更加持久。

WebDriverWait wait = new WebDriverWait(driver, 5);
final By lookup = By.id("radio");
LOG.debug("Wait for radio to be clickable.");
wait.until(ExpectedConditions.elementToBeClickable(lookup)); //I assume this implies visibility.
LOG.debug("Element clickable. Proceeding into click behavior.");
wait.until(new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver arg0) {
LOG.debug("Resolving 'myId' Element");
WebElement radio = arg0.findElement(lookup);
boolean rval = radio.isSelected();
LOG.debug("Element Resolved and has a state of " + (rval ? "selected" : "not selected"));
if (!rval) {
LOG.debug("Clicking on the Element!");
radio.click();
}
//If we return false we will loop. So the first time through we let this click the radio for us.
//Second time through we should find that the element is clicked. If it's not we click it again until it represents the state we're wanting.
return rval;;
}});

自定义谓词将

  1. 解析 WebElement
  2. 捕捉当前的Selected状态
  3. 如果未选中 WebElement,请单击它
  4. 返回当前选择的状态。

因此,在元素的单击状态达到我想要的状态之前,这不应该允许测试继续进行。到目前为止,它基本上完成了我想要的。

还值得注意的是,Thread.sleep 被视为不是 selenium 交互的最佳实践。这就是 ExplicitWait 概念要说明的问题。我已经链接了我知道正在讨论的最新主题之一。

Thread.sleep works but implicit wait, webdriverwait and fluent wait does not?

祝你好运!

关于java - Selenium 测试运行速度太快,没有等待单选按钮被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33127514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com