转换 Cucumber 中的数据表

Transform Tables of Data in Cucumber

我正在使用 Cucumber 为 spring 引导项目中的 Java 程序编写 BDD 测试。

将此 table 想象成用户给定数据的示例:

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.

有什么方法可以自动转换来自 table 的数据,包括值或 headers 用于具有更多列和行的 table 吗?

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

首先为映射数据创建一个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 class 将数据映射到 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]]

就这些了。