[Cucumber TestNG] Bài 11: Data Tables trong Cucumber theo ngôn ngữ Gherkin

✅ DataTables trong Cucumber là gì?
✅ Viết test cases Gherkin có chứa DataTables
✅ Xử lý DataTables trong code auto test

✅ DataTables trong Cucumber là gì?

DataTable trong Cucumber là một bảng dữ liệu được đính kèm với một step trong ngôn ngữ Gherkin của một Scenario. DataTable khá thú vị và có thể được sử dụng để triển khai data theo nhiều cách.

DataTables cũng được sử dụng để xử lý lượng lớn dữ liệu (nhiều rows). Chúng khá mạnh nhưng cũng cần chút thời gian nghiên cứu khi sử dụng vì bạn cần phải xử lý danh sách các key mapping với nhau trong code auto test sau đó.

Hầu hết mọi người bị nhầm lẫn giữa DataTableScenario Outline, nhưng hai cách này hoạt động hoàn toàn khác nhau.

Ví dụ DataTable trong Cucumber:

Feature: Handle DataTable

   Scenario: DataTable sample
      Given user on the login page
      When user enter valid credentials to login
         | username          | password |
         | user@example.com  | 123      |
         | admin@example.com | 123456   |
      Then user should be redirected to the admin page


✅ Viết test cases Gherkin có chứa DataTables

Feature: Login CMS

@InvalidLogin
Scenario: Invalid Login
  Given user on the login page
   When user enter an invalid username or password
    And click on the login button
   Then user should see an error message
    And stay on the login page

@InvalidLoginMultiple
Scenario: Invalid Login with multiple account
  Given user on the login page
   When user enter valid credentials to login
    | username          | password | 
    | user@example.com  | 123      | 
    | admin@example.com | 123456   | 
   Then user should see an error message
    And stay on the login page

 

Feature: Add Category

   Background: Login as Admin role
      Given user logged in as an admin

   Scenario: Add a new category
      Given user on the category page
      When user click on the Add Category button
      And user enter the category information
      And user click on the Save button
      Then user should see a success message
      And the new category should be displayed on the category page

   @AddCategoryMultiple
   Scenario: Add multi category
      Given user on the category page
      When the user adds some categories below
         | category_name | order_number | meta_title | description |
         | Computer 1    | 1            | Computer 1 | Build PC    |
         | Computer 2    | 2            | Computer 2 | Build PC    |
      Then the new category should be displayed on the category page
         | category_name | order_number | meta_title | description |
         | Computer 1    | 1            | Computer 1 | Build PC    |
         | Computer 2    | 2            | Computer 2 | Build PC    |


✅ Xử lý DataTables trong code auto test

Để xử lý DataTable từ Gherkin truyền vào code auto test thì chúng ta có 2 cách thiết kế:


🔆 Cách 1: sử dụng class DataTable của Cucumber

Bước 1: sử dụng class DataTable của Cucumber để có thể truyền data từ Gherkin xuống các Steps

import io.cucumber.datatable.DataTable;
@When("user enter valid credentials to login")
public void userEnterValidCredentialsToLogin(DataTable dataTable) {

}


Bước 2: sử dụng List kết hợp Map trong Java để duyệt data với các fields trên DataTable tương ứng

import java.util.List;
import java.util.Map;
@When("user enter valid credentials to login")
public void userEnterValidCredentialsToLogin(DataTable dataTable) {
    List < Map < String, String >> items = dataTable.asMaps();

    for (Map < String, String > item: items) {
        String email = item.get("username");
        String password = item.get("password");

        loginCMSPage.enterEmailAndPassword(email, password);
        loginCMSPage.clickLoginButton();
    }
}

 

  • Map là để lưu dữ liệu của một dòng trong table dạng <key, value>. Key là các fields name trong DataTable.
  • List dùng để lưu được nhiều dòng từ Map trên List<Map<key, value>>

🔆 Cách 2: sử dụng class POJO (model) của Java

Thiết kế class POJO cho từng bộ dữ liệu. Ví dụ dưới là cho bộ Login.

Lưu ý: nó sẽ chứa hàm xây dựngcác hàm Get tương ứng các fields name nhé. Và fields name phải giống với fields name trên DataTable.

package com.anhtester.models;

public class Credentials {
    private String username;
    private String password;

    public Credentials(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
}


Hoặc các bạn có thể sử dụng thư viện Lombok để xây dựng class POJO nhanh hơn.

Add thư viện Lombok từ maven:

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.26</version>
    <scope>provided</scope>
</dependency>


Thay đổi lại class POJO một chút và sử dụng các thành phần ghi chú trong Lombok hỗ trợ như sau:

package com.anhtester.models;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Credentials {
    private String username;
    private String password;
}


@Data
là dùng để tự động hiểu các hàm Get và Set
@NoArgsConstructor dùng để tự động khởi tạo hàm xây dựng không có tham số
@AllArgsConstructordùng để tự động khởi tạo hàm xây dựng có đủ các tham số

Việc khởi tạo các constructor mặc định không có tham số đầu vào là một trong những tác vụ chúng ta phải thực thi lặp đi lặp lại.

Chính vì vậy mà Lombok đã cung cấp một annotation giúp tự sinh các constructor mặc định là @NoArgsConstructor. Và tương tự thì @AllArgsConstructor giúp tự sinh các constructor có đủ tham số đầu vào.


Tiếp theo, tại class Steps Definitions chúng ta cần thiết lập 2 bước để có thể convert DataTable sang dạng Object class (POJO)

Bước 1
: thêm @DataTableType vào một hàm trung gian để nó tự động Transformer

Đặt tại chính class Step Definitions luôn nhé.

@DataTableType
public Credentials credentialsEntryTransformer(Map < String, String > row) {
    return new Credentials(row.get("username"), row.get("password"));
}


Bước 2: thêm List<POJO class> vào hàm chứa step DataTable

@When("user enter valid credentials to login")
public void userEnterValidCredentialsToLogin(List<Credentials> credentials) {

    for (Credentials credential: credentials) {
        String email = credential.getUsername();
        String password = credential.getPassword();

        loginCMSPage.enterEmailAndPassword(email, password);
        loginCMSPage.clickLoginButton();
    }
}


Như vậy tại class Steps Definitions sẽ như sau:

@DataTableType
public Credentials credentialsEntryTransformer(Map<String, String> row) {
    return new Credentials(row.get("username"), row.get("password"));
}

@When("user enter valid credentials to login")
public void userEnterValidCredentialsToLogin(List<Credentials> credentials) {

    for (Credentials credential : credentials) {
        String email = credential.getUsername();
        String password = credential.getPassword();

        loginCMSPage.enterEmailAndPassword(email, password);
        loginCMSPage.clickLoginButton();
    }
}
  • Anh Tester

    Đường dẫu khó chân vẫn cần bước đi
    Đời dẫu khổ tâm vẫn cần nghĩ thấu