2017-03-23 38 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) 
相關問題