Search code examples
javaspringtestingcucumberbdd

Transform Tables of Data in Cucumber


I'm working on Cucumber to write BDD tests for a Java program in a spring boot project.

Imagine this table as an example of user given data:

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

the problem comes in mapping data, where I'm calling an API which gets data as json and knows colour not color and gets S and L as size properties not small and large.

is there any way to auto convert data from tables, including values or headers for tables with more columns and rows?


Solution

  • Here I will share how I've done that:

    first create a POJO for mapping data:

    @Setter
    @Getter
    @NoArgsConstructor
    @AllArgsConstructor
    public class TshirtInfo {
    
        private String colour;
    
        private String size;
    
        @Override
        public String toString() {
            return "TshirtInfo [colour: " + colour + ", size: " + size + "]";
        }
    
    }
    

    then create a DataTransformer class to map data to 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);
                            }
                    )
            );
        }
    
    
    }
    

    finally for using them:

    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
    
    }
    

    Output would be like:

      | color | size  |
      | blue  | small |
      | black | large |
    
    [TshirtInfo [colour: blue, size: S], TshirtInfo [colour: black, size: L]]
    

    That's all.