Cucumber Compare Data Tables using diff and equals method

Profile picture for user devraj

You can compare data table with another data in tabular format. This data can be from excel, database or even from the REST services.

For this you need to convert List of Lists data using create method of Data Table class and later do the comparison using Diff or equals method.

Scenario

  @datatable
  Scenario: Verify user details
    #Given When I request "ah.programsbuzz.com/users"
    Then I gets following response
      | Username | Email |
      | U1       | E1    |
      | U2       | E2    |
      | U3       | E3    |

Data Table Create Method 

@Then("I gets following response")
public void i_gets_following_response(DataTable dataTable)
{
    List<List<String>> actualList = new ArrayList<List<String>>();
    actualList.add(Arrays.asList("Username", "Email"));
    actualList.add(Arrays.asList("U1", "E1"));
    actualList.add(Arrays.asList("U2", "E2"));
    actualList.add(Arrays.asList("U3", "E3"));

    DataTable actual = DataTable.create(actualList);
}

Data Table diff Method

If tables are different, TableDiffException will be thrown and difference will be displayed in console or execution report. Also, your test will fail if there is difference in table.

dataTable.diff(actual);

In below output, you can observe U4 record of data table differ from U3 and we got TableDiffException along with difference.

io.cucumber.datatable.TableDiffException: tables were different:
      | Username | Email |
      | U1       | E1    |
      | U2       | E2    |
    - | U3       | E3    |
    + | U4       | E3    |

	at io.cucumber.datatable.TableDiffException.diff(TableDiffException.java:12)
	at io.cucumber.datatable.DataTable.diff(DataTable.java:145)

Observe the minus (-) and (+) in console result. When 2 rows does not match it show difference like this.

Data Table equals Method

Data table equals method return true or false after data tables comparison. You have to use this along with Assert for your test to pass or fail.

Assert.assertTrue(dataTable.equals(actual));