在Cucumber中转换数据表格

问题描述 投票:0回答:1

我正在使用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,并且知道 colourcolor 并得到 SL 作为 size 无属性 smalllarge.

有什么方法可以自动转换表格中的数据,包括有更多列和行的表格的值或标题?

java spring cucumber bdd
1个回答
0
投票

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

首先创建一个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]]

就这样了

© www.soinside.com 2019 - 2024. All rights reserved.