Shorter way to assert boolean set in for loop

Viewed 52

Is there a way to make the code below simpler and shorter?

boolean clicked = false;
    for (WebElement anchor : anchorLinksForProducts) {
        if (anchor.getAttribute("href").contains(id)) {
            anchor.click();
            clicked = true;
            break;
        }
    }

    Assert.assertTrue(clicked, "Could not find a valid product link with id : " + id);
2 Answers

A stream should make the code shorter:

Optional<WebElement> anchor = 
    anchorLinksForProducts.stream()
                          .filter(a -> a.getAttribute("href").contains(id))
                          .findFirst();
if (anchor.isPresent()) {
    anchor.get().click();
} else {
    fail("Could not find a valid product link with id : " + id);
}

A refinement to @Mureinik's answer.

anchorLinksForProducts.stream()
    .filter(a -> a.getAttribute("href").contains(id))
    .findFirst()
    .ifPresentOrElse​(
        WebElement::click,
        () -> fail("Could not find a valid product link with id : " + id)
    );

There's a little more overhead in this code, but that is always the case with streams and not a problem if it is test code.

Related