【问题标题】:Transform Tables of Data in Cucumber在 Cucumber 中转换数据表
【发布时间】:2020-05-16 06:28:04
【问题描述】:

我正在 Cucumber 上为 Spring Boot 项目中的 Java 程序编写 BDD 测试。

将此表想象为用户给定数据的示例:

Given user wants to buy a T-shirt with the following attributes
  | color | size  |
  | blue  | small |
  | black | large |

问题出现在映射数据中,我调用的 API 获取数据为 json 并且知道 colour 而不是 color 并获取 SL 作为 size 属性而不是 smalllarge.

有没有办法自动转换表格中的数据,包括具有更多列和行的表格的值或标题?

【问题讨论】:

  • 创建自己的 pojo 类,然后添加 @DataTableType 以转换数据表数据,当您尝试从 pojo 对象访问数据时,在使用 getter 方法访问数据之前,您可以执行一些操作可以帮助您根据要求进行数据转换。

标签: java spring testing cucumber bdd


【解决方案1】:

在这里我将分享我是如何做到的:

首先为映射数据创建一个POJO:

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class TshirtInfo {

    private String colour;

    private String size;

    @Override
    public String toString() {
        return "TshirtInfo [colour: " + colour + ", size: " + size + "]";
    }

}

然后创建一个 DataTransformer 类将数据映射到 POJO:

public class DataTransformer implements TypeRegistryConfigurer {

    public DataTransformer () {
        this.map = new HashMap<>();
        this.map.put("small", "S");
        this.map.put("large", "L");
    }

    private Map<String, String> map;

    @Override
    public Locale locale() {
        return Locale.ENGLISH;
    }

    @Override
    public void configureTypeRegistry(TypeRegistry typeRegistry) {
        typeRegistry.defineDataTableType(new DataTableType(TshirtInfo.class,
                        (Map<String, String> row) -> {

                            String colour = row.get("color");
                            String size = this.map.get(row.get("size"));

                        return new LoginInfo(colour, size);
                        }
                )
        );
    }


}

终于使用它们了:

public class Stepdefs implements En {

    public Stepdefs () {

        Given("user wants to buy a T-shirt with the following attributes", (DataTable dataTable) -> {

            System.out.println(dataTable);

            List<TshirtInfo> infos = dataTable.asList(TshirtInfo.class);
            System.out.println(infos);

        .
        .
        .
        .
        // other parts of your code

}

输出如下:

  | color | size  |
  | blue  | small |
  | black | large |

[TshirtInfo [colour: blue, size: S], TshirtInfo [colour: black, size: L]]

就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多