Java - Gherkin&黄瓜:在垂直表格上传递对象或对象列表而不是水平

时间:2017-11-23 03:18:58

标签: java java-8 cucumber gherkin cucumber-java

我的功能文件中有以下示例小黄瓜场景:

Scenario: Book an FX Trade
 Given trades with the following details are created:
   |buyCcy |sellCcy |amount   |date       |
   |EUR    |USD     |12345.67 |23-11-2017 |
   |GBP    |EUR     |67890.12 |24-11-2017 |
 When the trades are executed
 Then the trades are confirmed

在我的胶水文件中,我可以将数据表映射到对象Trade,作为开箱即用的黄瓜解决方案:

@When("^trades with the following details are created:$")
public void trades_with_the_following_details_are_created(List<Trade> arg1) throws Throwable {
        //do something with arg1
}

我想要实现的目标:
通过执行以下操作提高我的小黄瓜方案的可读性:     

  • 垂直移调数据表,如果我的对象有大约10个字段,这将提高可读性     
  • 使用别名

    替换字段/列名称

    示例:

    Scenario: Book an FX Trade
     Given trades with the following details are created:
       |Buy Currency  | EUR        | GBP        |
       |Sell Currency | USD        | EUR        |
       |Amount        | 12345.67   | 67890.12   |
       |Date          | 23-11-2017 | 24-11-2017 |
     When the trades are executed
     Then the trades are confirmed
    

    我希望表格能够以多于或少于2个数据集/列的方式呈现动态。实现这一目标的最佳方法是什么?

    其他信息:
    语言:Java 8
    黄瓜版:1.2.5

    Trade POJO就像:

    public class Trade {
        private String buyCcy;
        private String sellCcy;
        private String amount;
        private String date;
    
        /**
         * These fields are growing and may have around 10 or more....
         * private String tradeType;
         * private String company;
         */
    
        public Trade() {
        }
    
        /**
         * accessors here....
         */
    }
    
  • 1 个答案:

    答案 0 :(得分:8)

    如果在功能文件中将表格指定为

    |buyCcy  | EUR        | GBP        |
    |sellCcy | USD        | EUR        |
    |amount  | 12345.67   | 67890.12   |
    |date    | 23-11-2017 | 24-11-2017 |
    

    您可以使用以下粘合代码(使用已发布的Trade类,假设已实施正确的toString()方法

    @Given("^trades with the following details are created:$")
    public void tradeWithTheFollowingDetailsAreCreated(DataTable dataTable) throws Exception {
        // transpose - transposes the table from the feature file
        // asList - creates a `List<Trade>`
        List<Trade> list = dataTable.transpose().asList(Trade.class);
        list.stream().forEach(System.out::println);
    }
    

    输出

    Trade{buyCcy=EUR, sellCcy=USD, amount=12345.67, date=23-11-2017}
    Trade{buyCcy=GBP, sellCcy=EUR, amount=67890.12, date=24-11-2017}