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接口。

转载于:https://www.cnblogs.com/SandyYu/archive/2013/01/06/2846459.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值