黄瓜DataTable执行差异的Java对象列表

时间:2018-11-27 16:52:48

标签: java bdd cucumber-jvm cucumber-java

让我们获得以下功能文件,

Feature: Search Employees

  Background: 
    Given following employees exists
      | id | name   | department | 
      | 1  | Jack   | HR         | 
      | 2  | Rachel | Finance    | 
      | 3  | Mike   | HR         | 
      | 4  | Emma   | IT         | 

  Scenario: Get Employees By Department

    Given user wants to get list employees in a department

     When searched for department = 'HR'

     Then following list of employees are returned
      | id | name | department | 
      | 1  | Jack | HR         | 
      | 3  | Mike | HR         | 

想象一下,接下来的步骤调用了一个REST端点,该端点返回JSON。

  

当搜索部门='HR'

这是repose JSON,

[
  {
    "id": 1,
    "name": "Jack",
    "department": "HR"
  },
  {
    "id": 3,
    "name": "Mike",
    "department": "HR"
  }
]

对应的Java类

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Employee {

  private Integer id;
  private String name;
  private String department;

}

在较旧版本的黄瓜(即1.2.4)中,我们可以执行DataTable.diff(List 实际),如下所示,

@Then("^following list of employees are returned$")
public void following_list_of_employees_are_returned(DataTable expectedEmployees) throws Throwable {

  List<Map<String, Object>> actualEmployees = new ArrayList<>();
  List<Employee> employees = response.as(Employee[].class);

  employees
      .forEach(e -> {
        Map<String, Object> map = new HashMap<>();
        map.put("id", e.getId());
        map.put("name", e.getName());
        map.put("department", e.getDepartment());

        actualEmployees.add(map);
      });

  expectedEmployees.unorderedDiff(actualEmployees);
}

当前,我们已升级到以下黄瓜版本

<dependency>
  <groupId>io.cucumber</groupId>
  <artifactId>cucumber-java8</artifactId>
  <version>4.0.0</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>io.cucumber</groupId>
  <artifactId>cucumber-spring</artifactId>
  <version>4.0.0</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>io.cucumber</groupId>
  <artifactId>cucumber-junit</artifactId>
  <version>4.0.0</version>
  <scope>test</scope>
</dependency>

[INFO] +- io.cucumber:cucumber-java8:jar:4.0.0:test
[INFO] |  +- io.cucumber:cucumber-java:jar:4.0.0:test
[INFO] |  \- net.jodah:typetools:jar:0.5.0:test
[INFO] +- io.cucumber:cucumber-spring:jar:4.0.0:test
[INFO] \- io.cucumber:cucumber-junit:jar:4.0.0:test
[INFO]    \- io.cucumber:cucumber-core:jar:4.0.0:test
[INFO]       +- io.cucumber:cucumber-html:jar:0.2.7:test
[INFO]       +- io.cucumber:gherkin:jar:5.1.0:test
[INFO]       +- io.cucumber:tag-expressions:jar:1.1.1:test
[INFO]       +- io.cucumber:cucumber-expressions:jar:6.1.0:test
[INFO]       \- io.cucumber:datatable:jar:1.1.3:test
[INFO]          \- io.cucumber:datatable-dependencies:jar:1.1.3:test
  

问题::在黄瓜1.2.4版本中,可以将DataTable与List 进行比较。在较新版本(4.0.0)中,   DataTable.diff期望将DataTable作为参数,并且没有方法   支持差异列表。

     

现在,我们需要从List 。这样我们就可以执行ExpectedDataTable.diff(actualDataTable)。

     

问题::是否有一种简单的方法来转换JSON对象数组或   List 到DataTable,以便我们可以对2个数据表进行比较,而无需从需要大量代码的对象列表中创建List >。

2 个答案:

答案 0 :(得分:4)

完全公开:我为Cucumber编写了数据表模块。

手动在数据表之间映射对象非常耗时,无聊且容易出错。这最好留给对象映射器。另外,用于将表与List<Map<String, String>>进行比较的实现包含魔术,喷火器和陷阱。因此,我认为最好将其省略。

解决方案1 ​​

您要做的第一件事是upgrade to v4.2.0

然后将以下配置放在粘合路径上的某个位置。对象映射器来自Jackson。它通常随Spring一起提供。

public class ParameterTypes implements TypeRegistryConfigurer {

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

    @Override
    public void configureTypeRegistry(TypeRegistry typeRegistry) {
        Transformer transformer = new Transformer();
        typeRegistry.setDefaultDataTableCellTransformer(transformer);
        typeRegistry.setDefaultDataTableEntryTransformer(transformer);
        typeRegistry.setDefaultParameterTransformer(transformer);
    }

    private class Transformer implements ParameterByTypeTransformer, TableEntryByTypeTransformer, TableCellByTypeTransformer {
        ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public Object transform(String s, Type type) {
            return objectMapper.convertValue(s, objectMapper.constructType(type));
        }

        @Override
        public <T> T transform(Map<String, String> map, Class<T> aClass, TableCellByTypeTransformer tableCellByTypeTransformer) {
            return objectMapper.convertValue(map, aClass);
        }

        @Override
        public <T> T transform(String s, Class<T> aClass) {
            return objectMapper.convertValue(s, aClass);
        }
    }
}

然后将@Getter@Setter替换为@Data,以便实现hashcodeequalstoString

@Data
public class Employee {

  private Integer id;
  private String name;
  private String department;

}

然后修改您的步骤以使用雇员列表而不是数据表。上一步中安装的对象映射器将处理从数据表到对象的转换。

@Then("^following list of employees are returned$")
public void following_list_of_employees_are_returned(List<Employee> expectedEmployees) throws Throwable {    
  List<Map<String, Object>> actualEmployees = new ArrayList<>();
  List<Employee> employees = response.as(Employee[].class);
  assertEquals(expectedEmployees, actualEmployees);
}

要使比较顺序不敏感,请考虑使用AssertJs assertThat而不是JUnits assertEquals-它通常是Spring附带的

解决方案2

datatable-matchers添加到您的依赖项中

<groupId>io.cucumber</groupId>
<artifactId>datatable-matchers</artifactId>

创建自己的数据表,并使用DataTableHasTheSameRowsAs匹配器进行比较。

@Then("^following list of employees are returned$")
public void following_list_of_employees_are_returned(DataTable expectedEmployees) {
    List<Employee> employees = response.as(Employee[].class);

    DataTable actualEmployees = createTable(
            employees,
            asList("id", "name", "department"),
            Employee::getId, Employee::getName, Employee::getDepartment
    );
    assertThat(actualEmployees, hasTheSameRowsAs(expectedEmployees));
}


static <T> DataTable createTable(List<T> values, List<String> headers, Function<T, Object>... extractors) {
    List<List<String>> rawTable = new ArrayList<>();
    rawTable.add(headers);
    values.stream()
            .map(employee -> Stream.of(extractors)
                    .map(f -> f.apply(employee))
                    .map(String::valueOf)
                    .collect(Collectors.toList()))
            .forEach(rawTable::add);
    return create(rawTable);
}

答案 1 :(得分:0)

很好的答案,我有与您相同的解决方案,但我遇到了一种情况: 假设我们有:

public class Employee {

  private Integer id;
  private String name;
  private List<String> department;

}

有什么办法可以做这样的测试:

     Then following list of employees are returned
      | id | name | department | 
      | 1  | Jack | HR, IT     | 
      | 3  | Mike | HR         | 

意思是如何告诉小黄瓜我有部门的名单?

顺便说一下,对于您的具体情况,因为您没有使用 List 或 Hashset,您可以只使用:

    @DefaultParameterTransformer
    @DefaultDataTableEntryTransformer(replaceWithEmptyString = "[blank]")
    @DefaultDataTableCellTransformer
    public Object transformer(Object fromValue, Type toValueType) {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.convertValue(fromValue, objectMapper.constructType(toValueType));
    }

并将其添加到步骤定义中,无需创建 ParameterTypes 类