Search code examples
javaselenium-webdriverautomated-testsassertassertion

Assert that element from List<webelement> contains some text


I'm not sure how can I assert that I have a list of webelements where each webelement has the text inside, And I want to verify that on this list of webelements exists some text.

I not sure how this should looks assertion in this case.


Solution

  • Simple get stream, map to string (text) and check if any matches:

    boolean anyMatch = webelements.stream()
      .map(WebElement::getText)
      .anyMatch(text -> "inside".equals(text));
    

    To be safe filter out null's and trim:

    boolean anyMatch = webelements.stream()
      .map(WebElement::getText)
      .filter(Objects::nonNull)
      .map(String::trim)
      .anyMatch(text -> "inside".equals(text));