Search code examples
javaselenium-webdrivercucumber

Compare dataTable with List of strings


I'm using Selenium & Cucumber and I'm trying to use DataTables functionality. The idea is to test all footer links with schema like:

  Scenario: I verify footer links
    * I verify that links section inside the footer are visible
      | Colofon                          |
      | Gegevensbescherming              |
      | FAQ/ Hulp                        |
      | Contact                          |

And for now my code looks like:

@And("I verify that links section inside the footer are visible")
public void iVerifyThatLinksSectionAreCorrect(DataTable dataTable) {
    List<String> nlLinksSection = dataTable.asList();
    List<WebElement> nlLinks = baseMethods.findElements("FooterNL.Links");

    List<String> nlLinksString = new ArrayList<>();
    nlLinks.stream().map(WebElement::getText).forEach(nlLinksString::add);

    Assert.assertTrue(CollectionUtils.isEqualCollection(nlLinksSection, nlLinksString));
}

Actually the method & assertion works but in case of mismatching (dataTable & WebElement) I'm recieving something like:

Step failed
java.lang.AssertionError: expected [true] but found [false]

I have two questions:

  • Can this method be written in better & more clear way? I feel it does not look really good...
  • Can someone tell me how I can improve assertion to implement messages like: "Comparison failed, there should be: "Contact" element but was not" or "Comparison failed, there should be: "Contact" element but was: "XYZ"

Solution

  • I'd recommend to switch to AssertJ framework, which provides the functionality you need out of the box. You could then use something like

    Assertions.assertThat(nlLinksSection).containsExactly(nlLinksString);

    This assertion will provide a very good error message telling you what's wrong, but you can freely override it yourself like this:

    Assertions.assertThat(nlLinksSection)
            .overridingErrorMessage("nlLinksSection " + nlLinksSection + " is a bit different than nlLinksString " + nlLinksString)
            .containsExactly(nlLinksString);
    
    

    Shorter way of mapping nlinks to List<String> may look like

    List<String> nlLinksString = nlLinks.stream().map(WebElement::getText).collect(Collectors.toList());