如何将字符串变量插入到 Cucumber-JVM 中的步骤定义中?

How do I insert a string variable into my step definition in Cucumber-JVM?

我想使用 java 将预定义的字符串插入到 Cucumber 中的步骤定义中。这是我拥有的:

Java代码

public String temp = "hello";
//insert temp into my step:
@Then("^the "+temp+" should be empty$")
public void the_should_be_empty() throws Throwable {
    //do things
}

但我不断收到此 错误:

"The value for annotation attribute Then.value must be a constant expression"

那么,如何将字符串插入 我的捕获步骤

=============

更多信息

我试图在我的许多 BDD 步骤定义中使用 "global keywords" 的集合列表。所以当我添加一个新的 "global keyword" 时,它会在我所有的 BDD 中改变。例如 (red|yellow|green) 可用于 10 个不同的 BDD 步骤,我想添加 blue 而不更改所有 10 个步骤。相反,我想要一个包含列表的字符串变量,然后将此变量插入我的 BDD。

简短的回答是:"You don't"。

较长的是注解中的值必须是常量。它不可能是构建 运行 时间的东西。

Cucumber 匹配 Java 和场景之间的步骤的方式是使用您在注释中定义的正则表达式。如果构建值 运行 次,则该过程失败。 Cucumber 运行ner 将定位并使用在步骤实现中找到的所有正则表达式,然后搜索功能文件以将代码与场景步骤匹配。

这就是为什么您无法构建字符串以匹配 运行 时间的原因。

了解为什么要构建字符串 运行 时间会很有趣。你想达到什么目的? 创建许多不同字符串的结果是您的场景中必须有许多应该匹配的不同步骤。对我来说,感觉你误解了什么。请分享您想要实现的目标,也许我们可以通过其他方法帮助您。

您可以使用 custom parameter type

定义后,您的步骤定义将如下所示:

@Then("the {color} should be empty")
public void the_should_be_empty(Color color) throws Throwable {
    //do things
}

现在,如果颜色列表发生变化,您不必编辑每个 stepdef。