gpt4 book ai didi

java - 如何最好地使用 ExpectedConditions.or 和可变数量的条件

转载 作者:行者123 更新时间:2023-12-02 09:38:31 24 4
gpt4 key购买 nike

我一直在使用 ExpectedConditions.or 。例如,查找一个或另一个元素是否存在是非常有用的。我现在想做的是使用变量参数构建一个更灵活的方法。

看看我在下面做了什么。它可以工作......就这样,但我想要一个更优雅的解决方案,实际上可以处理任意数量的元素。

public void waitForSomeElementToBeVisible(int timeout, final By... locators) throws Exception, TimeoutException {
boolean found = false;

try {
waitUntilJSReady();
setImplicitWait(0);
WebDriverWait wait = new WebDriverWait(driver, timeout);
if (1 == locators.length) {
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(locators[0]));
found = null == element ? false : true;
} else if (2 == locators.length) {
found = wait.until(ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(locators[0]),
ExpectedConditions.visibilityOfElementLocated(locators[1])));
} else if (3 == locators.length ) {
found = wait.until(ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(locators[0]),
ExpectedConditions.visibilityOfElementLocated(locators[1]),
ExpectedConditions.visibilityOfElementLocated(locators[2])));
} else if (4 == locators.length ) {
found = wait.until(ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(locators[0]),
ExpectedConditions.visibilityOfElementLocated(locators[1]),
ExpectedConditions.visibilityOfElementLocated(locators[2]),
ExpectedConditions.visibilityOfElementLocated(locators[3])));
}
} catch (Exception e) {
// log...whatever
throw e;
} finally {
setImplicitWait(SelTestCase.WAIT_TIME_OUT);
}
if (!found) throw new TimeoutException("Nothing found");
}

最佳答案

您可以在运行时获取定位器的数量,并在 for 循环中使用它们。

在下面的代码中,我创建了包含 ExpectedCondition[] 的数组。在 until 方法中使用它们之前将它们存储起来,然后将其传递给 until

这可以让你摆脱if-else:)

public void waitForSomeElementToBeVisible(int timeout, final By... locators) throws Exception, TimeoutException {
boolean found = false;

try {
waitUntilJSReady();
setImplicitWait(0);
WebDriverWait wait = new WebDriverWait(driver, timeout);

ExpectedCondition<?>[] conditionsToEvaluate = new ExpectedCondition[locators.length];
for (int i = 0; i < locators.length; i++) {
conditionsToEvaluate[i] = ExpectedConditions.visibilityOfElementLocated(locators[i]);
}

found = wait.until(ExpectedConditions.or(conditionsToEvaluate));
} catch (Exception e) {
// log...whatever
throw e;
} finally {
setImplicitWait(SelTestCase.WAIT_TIME_OUT);
}
if (!found) throw new TimeoutException("Nothing found");
}

希望对你有帮助!

关于java - 如何最好地使用 ExpectedConditions.or 和可变数量的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299524/

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