将错误数量的参数从 Gherkin 功能文件映射到步骤定义

Mapping wrong number of parameter from Gherkin features file to step definition

我有这样的功能声明:

    Feature: find taxi and minicabs information
  in order to get taxi and minicabs contact at given location
  as application developer
  I want to find tax and minicabs contact information at given location or query options

  Scenario Outline: find taxi and minicabs contact information
    Given Joe at location with <lat> and <lon>
    When get all taxi and minicabs contacts information
    Then should see list of taxi and minicabs
    And all of them are at location with <lat> and <lon>
    Examples:
      | lat       | lon       |
      | 51.490075 | -0.133226 |

我有这样的步骤定义:

@Given("^Joe at location with ([+-]?([0-9]+[.])?[0-9]+) and ([+-]?([0-9]+[.])?[0-9]+)$")
public void joeAtLocationWithLatAndLon(Number lat, Number lon) throws Throwable {
  ....
}

我原以为我可以收到 2 个参数,但 Cucumber 传递给我的是 4 个参数。 报错如下:

 with pattern [^Joe at location with ([+-]?([0-9]+[.])?[0-9]+) and ([+-]?([0-9]+[.])?[0-9]+)$] is declared with 2 parameters. However, the gherkin step has 4 arguments [51.490075, 51., -0.133226, 0.]. 

你有什么想法吗?顺便说一句,如果你能解释黄瓜识别参数数量的方式或与我分享任何相关文件,我将非常感激。

问题是正则表达式中的两个内括号。使用当前的正则表达式,您将得到 2 组 - 一组是整个“51.490075”,第二组是“51”。与 ([0-9]+[.]) 部分中的 exp 相匹配。因此创建了 4 个参数。

去掉里面的括号,每个参数只有一个参数,所以总共有两个。

您将遇到的下一个问题是 Cucumber 不知道如何将 String 转换为 Number class 除非您告诉它。为此,您需要使用 Transform 注释并为此创建一个特定的 class。

import cucumber.api.Transformer;

public class NumberTransformer extends Transformer<Number>{

    @Override
    public Number transform(String value) {
        return Double.parseDouble(value);
    }
}

@Given("^Joe at location with ([+-]?[0-9]+[.]?[0-9]+) and ([+-]?[0-9]+[.]?[0-9]+)$")
    public void joeAtLocationWithAnd(@Transform(NumberTransformer.class)Number arg1, @Transform(NumberTransformer.class)Number arg2) throws Exception {
        System.out.println(arg1);
        System.out.println(arg2);
    }

转换问题也可以查xstreams。如果您使用的是 Cucumber 2,则使用 Xstreamconvertor 注释可以更轻松地进行此类转换 - https://github.com/cucumber/cucumber-jvm/pull/1010