Search code examples
javacucumbergherkin

Java - Gherkin & Cucumber : Pass Object with arrayList of objects


i have the following java model :

public class User {

  private String name;

  private String password;


  private List<Comment> commentsList;
  
}


public class Comment {

  private Long id;
  private String description;

}

i want to know how i can write my gherkin data for a user with 2 comments object as a datatable.


Solution

  • Something like this should work

    Scenario: User with 2 comments
    Given I have a User
      | name | password |
      | John | pass     |
    And users have the following comments
      | id | description |
      | 1  | first       |
      | 2  | second      |
    

    With Step definition sample as

        User user;
    
        @Given("I have a User")
        public void iHaveAUser(Map<String, String> userData) {
            User user = new User();
            user.setName(userData.get("name"));
            user.setPassword(userData.get("password"));
            List<Comment> commentsList = new ArrayList<>();
            user.setCommentsList(commentsList);
            this.user = user;
            // Save the user object for later use
        }
    
        @And("users have the following comments")
        public void usersHaveTheFollowingComments(List<Map<String, String>> commentsData) {
    
            List<Comment> commentsList = this.user.getCommentsList();
            // Map the datatable to Comment objects and add them to the list
            for (Map<String, String> commentData : commentsData) {
                Comment comment = new Comment();
                comment.setId(Long.valueOf(commentData.get("id")));
                comment.setDescription(commentData.get("description"));
                commentsList.add(comment);
            }
        }