为SpecFlow测试运行中的所有功能存储全局变量

时间:2015-07-31 15:59:08

标签: bdd specflow gherkin scenarios

我一直在使用FeatureContext存储有关特定功能的信息,该功能可以在该功能的所有方案中重复使用。但是我有一些事情,比如登录信息,我不想为每个功能重新创建。我想使用[BeforeTestRun]属性来存储它,但SpecFlow是否具有某种全局上下文功能(如log4net)来存储此信息,以便所有功能都可以重用它?

1 个答案:

答案 0 :(得分:2)

SpecFlow doesnt have a global context construct, however you have a few options that can help you share data between bindings/features:

Static members

You can use static field/property to set objects that can be used across all features during test execution. Keep thread safety in mind however, because if you run your tests in parallel you need to synchronize initialisation and any mutable access to this field. If you want this data to change per scenario you can set the object in the context when accessed, this way you can set a default, and allow the scenario to have its own copy.

Context injection

You can use SpecFlow Context injection to inject a object into step definitions via the constructor, this way you can initialize your type using its default constructor and the pass the type into the step def like so:

[Binding]
public class MyStepDefinition
{
    private readonly MyContextData contextData;

    public MyStepDefinition(MyContextData contextData)
    {
        this.contextData = contextData;
    }
}

more info:

https://github.com/techtalk/SpecFlow/wiki/Sharing-Data-between-Bindings