黄瓜中的正则表达式匹配但不捕获它

Regex match in cucumber but not capture it

我正在使用 specflow 使用 Gherkin 语法编写我的浏览器测试。我有一个步骤定义,我想在其中匹配 2 个不同的步骤但不捕获它。例如:

Scenario:
  Given I have some stuff
  And I click on the configure user 
  And I configure user
  And I set the user <config> to <value>
  Then I should see user configuration is updated

Scenario:
  Given I have some stuff
  And I click on the configure admin
  And I configure admin
  And I set the admin <config> to <value>
  Then I should see user configuration is updated

And I set the admin <config> to <value> 的步骤定义正则表达式类似于:

Given(@"And I set the admin (.*) to (.*)")
public void AndISetTheAdminConfigToValue(string config, string value) 
{
    // implementation
}

And I set the user <config> to <value> 就像:

Given(@"And I set the admin (.*) to (.*)")
public void AndISetTheUserConfigToValue(string config, string value) 
{
    // implementation
}

两个步骤的实现是一样的。所以我想做的是:

Given(@"And I set the user|admin (.*) to (.*)")
public void AndISetTheConfigToValue(string config, string value) 
{
    // implementation
}

上面的代码将不起作用,因为 configvalue 参数将是空字符串,因为 useradmin 被捕获为前 2 个参数。

有没有办法在不捕获参数中的正则表达式匹配的情况下执行上述操作?

我知道我可以简单地重写场景如下来解决问题。不过我只是好奇。

Scenario:
  Given I have some stuff
  And I click on the configure admin
  And I configure admin
  And I set the <config> to <value>
  Then I should see user configuration is updated

首先要小心在同一个绑定中有多个 (.*),因为它会导致捕获错误的模式。

无需检查,我很确定可以在该方法上提供多个绑定,只要它们具有相同的参数计数,即

 [Given("I set the user (.*) to (.*)"]
 [Given("I set the admin (.*) to (.*)"]
 public void ISetTheConfigValue(string config, string value)  

或者,您始终可以添加一个虚拟参数,

 [Given("I set the (user|admin) (.*) to (.*)"]
 public void ISetTheConfigValue(string _, string config, string value)

使用 AlSki 提供的作为基准:

在这里也可以选择使用可选组:

[Given(@"I set the (?:user|admin) (.*) to (.*)"]
public void ISetTheConfigValue(string config, string value)

这意味着您不必包含永远不会使用的参数。

我建议摆脱讨厌的 (.*) 正则表达式,它会匹配您放入其中的所有内容 - 如果您想要一个获取该用户可以获取的特权的步骤,稍后会出现问题有(例如):

Given I set the user JohnSmith to an admin with example privileges

所以我个人会使用这个:

[Given(@'I set the (?:user|admin) "([^"]*)" to "([^"]*)"']
public void ISetTheConfigValue(string config, string value)

哪个会匹配:

Given I set the user "JohnSmith" to "SysAdmin"
And I set the admin "JaneDoe" to "User"

但不匹配

Given I set the user JohnSmith to an admin with example privileges