SpecFlow特性介绍1-Step Definitions
我在項目中只用到其中部分的特性,接下來寫一下我使用SpecFlow這個工具所用到的一些特性。可能很多地方還需要改善,歡迎用過得朋友提建議。
(SpecFlow的wiki上有它的Documentation全面的介紹,有興趣的朋友也可以看看:https://github.com/techtalk/SpecFlow/wiki/Documentation)
Step Definitions:這是SpecFlow最基本的特性。Step Definitions通過綁定(Bindings)來把自然語言的規范(Specification)和應用程序接口鏈接起來。
正則表達式:在實際項目中我們會遇到很多類似的語句,比如下面2個步驟
When I click the 'Login' button"
When I click the 'Register' button"
…….
還有其他button的點擊步驟,如果每個都單獨實現腳本,可能如下:
[When("I click the 'Login' button")]
public void AndIClickTheLoginButton()
{
? var loginButton = WebBrowser.Current.Button(Find.ByValue("Login"));
? if(!loginButton.Exists)
??? Assert.Fail("Expected to find a button with the value of 'Login'.");
? loginButton.Click();
}
[When("I click the 'Register' button")]
public void AndIClickTheRegisterButton()
{
? var registerButton = WebBrowser.Current.Button(Find.ByValue("Register"));
? if(!registerButton.Exists)
??? Assert.Fail("Expected to find a button with the value of 'Register'.");
? registerButton.Click();
}
可以看出的是我們腳本存在大量的重復,測試也需要重構。幸運的是SpecFlow提供了參數話來避免這個問題。這里每個步驟都是WatiN通過找到某個button,然后點擊它。我們就可以用正則表達式捕捉到button的一些屬性,然后把這個屬性作為參數傳給step definition方法。例如:
[When("I click the '(.*)' button")]
public void AndIClickAButton(string buttonText)
{
? var button = WebBrowser.Current.Button(Find.ByValue(buttonText));
? if(!button.Exists)
??? Assert.Fail("Expected to find a button with the value of '{0}'.", buttonText);
? button.Click();
}
?
多標記:有時很多Steps步驟的描述很類似卻不完全相同,但是實現方法類似。我們可以在同一個方法上標記多個steps的描述性語句。例如:
[Given(@"I create a new general activity")]
[When(@"I create a new general activity")]
public void WhenICreateANewGeneralActivity()
{
?? //some test code here….
}
表格參數:在步驟中可以使用表格形式的參數,可以讓scenario更直接明了,例如:
Scenario: Fill Machine With Coffee, Chocholate And Tea
??? Given I have filled machine with
??????? |Drink??????? |Count??? |
??????? |Coffee??????? |5??????? |
??????? |Tea??????? |2??????? |
??????? |Chocholate??? |3??????? |
??? When I press the service button
??? Then I should get a message "There are 10 drinks in the machine"
綁定的測試方法如下:
[Given(@"I have filled machine with")]
public void GivenIHaveFilledMachineWith(Table table)
{
??? foreach (var row in table.Rows)
??? {
??????? if (row[0] == "Coffee")
??????? {
??????????? target.LoadCoffee(int.Parse(row[1]));
??????? }
??????? if (row[0] == "Tea")
??????? {
??????????? target.LoadTea(int.Parse(row[1]));
??????? }
??????? if (row[0] == "Chocholate")
??????? {
??????????? target.LoadChocholate(int.Parse(row[1]));
??????? }
??? }
}
這是幾種常見Step Definitions的做法,下篇繼續介紹Binding相關的特性
轉載于:https://www.cnblogs.com/SandyYu/archive/2013/01/04/2842558.html
總結
以上是生活随笔為你收集整理的SpecFlow特性介绍1-Step Definitions的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 没事影视电(没事影视在线观看)
- 下一篇: OD使用教程18 - 调试篇18