Multiple column datatable in Cucumber

Now let us look at how to pass the data table with multiple columns in Cucumber.

Feature: Multiple column data table
  Scenario: Create new student records
  Given We have below list of students
  | name          | id        | address |
  | sagar         | 288345    |Brisbane |
  | watson        | 38829     | London  |
  | paul          | 34223     |Chicago  |

Now take a look at below Student Class. This class is mapped with the data table.

package org.softpost;

/**
 * Created by Sagar on 13-07-2016.
 */
public class Student {
    private String name;
    private String address;
    private int id;

    public Student(String name, int id, String address) {
        this.name = name;
        this.id = id;
        this.address = address;
    }

    public void printStudent(){
        System.out.println("\nStudent -> " + name +", " + id + ", " + address);
    }
}

Now look at the step definition class. Note how we have converted the Data table to the list of student objects.

package org.softpost;

import cucumber.api.DataTable;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;

import java.util.List;
import java.util.Map;

/**
 * Created by Sagar on 13-07-2016.
 */
public class DatatableSteps {


    @Given("^We have below list of students$")
    public void we_have_below_list_of_students(DataTable arg1) throws Throwable {
        List<Student> students = arg1.asList(Student.class);

        for(Student s : students){
            s.printStudent();
        }
    }

}

Here is the output of above code.

Testing started at 19:48 …

Student -> sagar, 288345, Brisbane

Student -> watson, 38829, London

Student -> paul, 34223, Chicago
1 Scenarios (1 passed)
1 Steps (1 passed)
0m0.635s

You may also like...