0

我一直在使用 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");
    }
4

1 回答 1

1

您可以在运行时获取定位器的数量并在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");
    }

希望能帮助到你!

于 2019-08-01T05:11:12.073 回答