2017-03-23 41 views
0

我正在使用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 
+0

场景的重写看起来同样喜欢原始方案。减价格式是否删除了一些字符? –

回答

1

使用什么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 
+0

我相信我一直在寻找'[Given(@'我设置(?:user | admin)“([^”] *)“为”([^“] *)”']'。 – Subash

2

首先要注意有多个(.*) S IN相同的约束力的,因为它可以导致捕获错误的图案。

,不检查我敢肯定,这是可以提供多个绑定的方法,只要它们具有相同的参数个数,即

[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) 
相关问题