简体   繁体   中英

I don't know how in a better way to check that my List<WebElement> has more then one item in a loop (counting by time is not prefer)

I have implemented waiter for List<WebElement> by presenceOfAllElementsLocatedBy condition. It looks like:

    protected List<WebElement> waitForElements(By locator, WaitConditionForWebElements condition){

       return  elements = wait.until(condition.getType().apply(locator));

}

I'm stumbling over an issue that sometimes my method returns a List just with one element immediately after redirecting to a new page (page was loaded), but in a several seconds current List<WebElement> has several elements (as expected). So, I have changed my method by adding a do while statement and strange counter (note: I don't want to fasten counter to sleep time). See what I got:

protected List<WebElement> waitForElements(By locator, WaitConditionForWebElements condition){

    List<WebElement> elements;
    int counter = 1;
    do {

         elements = wait.until(condition.getType().apply(locator));

         //System.out.println(elements.size());

        counter++;

    } while ((elements.size() == 1) && (counter < 30));

    return elements;

}

It works, but I clearly feel that it is not a good way. Ideal, as I think, will be construction kind of default waiter (condition, wait time). Looking forward to any advice.

I have written my own Expected condition:

public class CustomExpectedCondition {

public static ExpectedCondition<List<WebElement>> moreThanOne(
        final By locator) {
    return driver -> {
        List<WebElement> elements = getDriver().findElements(locator);
        return elements.size() > 1 ? elements : null;
    };

}
}

After that I have wrapped that in a Function<By, ExpectedCondition<List<WebElement>> :

@Getter
@RequiredArgsConstructor
public enum WaitConditionForWebElements {

    allPresenceExtended(CustomExpectedCondition::moreThanOne);

    private final Function<By, ExpectedCondition<List<WebElement>>> type;

}

After that you could use it in your wait methods, for example:

protected List<WebElement> waitForElements(By locator, WaitConditionForWebElements condition){

    return wait.until(condition.getType().apply(locator));

}

At the end of this chain you could take a look at example in a PageObject:

private List<WebElement> buttons(){

    return waitForElements(buttonsLocator, allPresenceExtended);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM