SpecFlow特性介绍2-Context
应用SpecFlow做Acceptance Test的时候经常遇到不同的Step之间传递数据,例子:
Feature: Components
As a logged in user
I want to be able to add new components
So that I can perform asssessments on them
@LogIn
@SetCurrentSection
Scenario: Add new component
Given I am on the components page
When I add a new component
Then the component should be added to the overview
我们在When中创建了一个component名字(或者Title)TestName,在Then步骤中我需要查找到这个名字TestName。
下面介绍几种常用的方法:
实例字段:SpecFlow可以创建一个对象实例,该类包括所有的Scenario steps在一个class中,这样我们可以使用私有字段来在不同方法中传递数据。下面例子来自SpecFlow wiki:
[Binding] public class SearchSteps { private ActionResult actionResult; [When(@"I perform a simple search on '(.*)'")] public void WhenIPerformASimpleSearchOn(string searchTerm) { var controller = new CatalogController(); actionResult = controller.Search(searchTerm); } [Then(@"the book list should exactly contain book '(.*)'")] public void ThenTheBookListShouldExactlyContainBook(string title) { var books = actionResult.Model<List<Book>>(); CustomAssert.Any(books, b => b.Title == title); } }
上下文连接:SpecFlow提供了2个Context实例, ScenarioContext, FeatureContext.
我们可以使用ScenarioContext为一个scenario创建实例,它会在Scenario执行完后自动销毁。类似FeatureContext在第一个scenario时创建,并且整个feature执行完后销毁。我一般使用多的是ScenarioContext。我们回到开头提到的例子。这里When和Then放在不同的class中,没法使用之前的私有成员来在不同的方法传递数据。
[Binding]
class ComponentsWhen
{
[When(@"I add a new component")]
public void WhenIAddANewComponent()
{
var page = WebBrowser.Current.Page<ComponentsPage>();
var driver = new ComponentsDriver(page);
string componentName = "Test Component Name" + new Random().Next(100);
ScenarioContext.Current.Set<string>(componentName, TestConstants.ContextKeys.ComponentName);
driver.AddNewComponent(componentName);
}
}
[Binding]
public class ComponentsThen
{
[Then(@"the component should be added to the overview")]
public void ThenTheComponentShouldBeAddedToTheOverview()
{
var page = WebBrowser.Current.Page<ComponentsPage>();
var driver = new ComponentsDriver(page);
string componentName = ScenarioContext.Current.Get<string>(TestConstants.ContextKeys.ComponentName);
page.ComponentsTable.WaitUntil(x => x.Enabled);
Assert.That(page.ComponentsTable.ContainsText(componentName), "Expected component name: " + componentName);
}
}
我们的做法是在When步骤设置ScenarioContext.Current对象,我们可以看出ScenarioContext继承Dictionary<string, object>, 并时间 IDisposable接口。