public class BaseSteps : Steps
{
[BeforeFeature]
public static void BeforeFeatureStep()
{
var otherStep = new OtherStep();
otherStep.ExecuteStep();
}
}
public class OtherStep : Steps
{
public void ExecuteStep()
{
var key = 'key';
var val = 'val';
this.FeatureContext.Add(key, val);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例片段。当我尝试访问时this.FeatureContext.Add(),出现异常Container of the steps class has not been initialized
对此的任何帮助表示赞赏。
FeatureContext 未初始化,因为 Step 类未由 SpecFlow DI 容器解析。因此,不会调用 SetObjectContainer 方法(https://github.com/techtalk/SpecFlow/blob/master/TechTalk.SpecFlow/Steps.cs#L10)。
作为一般规则,您不应自行实例化步骤类,而应通过上下文注入 ( http://specflow.org/documentation/Context-Injection ) 获取它们。
但在您的情况下这是不可能的,因为您处于 BeforeFeature 挂钩中。
一个可能的解决方案是使用最新的 SpecFlow 预发布版 ( https://www.nuget.org/packages/SpecFlow/2.2.0-preview20170523 )。在那里你可以通过钩子方法中的参数获取FeatureContext。它看起来像这样:
[BeforeFeature]
public static void BeforeFeatureHook(FeatureContext featureContext)
{
//your code
}
Run Code Online (Sandbox Code Playgroud)
您的代码可能如下所示:
public class FeatureContextDriver
{
public void FeatureContextChanging(FeatureContext featureContext)
{
var key = 'key';
var val = 'val';
featureContext.Add(key, val);
}
}
[Binding]
public class BaseSteps : Steps
{
[BeforeFeature]
public static void BeforeFeatureStep(FeatureContext featureContext)
{
var featureContextDriver = new FeatureContextDriver();
featureContextDriver.FeatureContextChanging(featureContext);
}
}
[Binding]
public class OtherStep : Steps
{
private FeatureContextDriver _featureContextDriver;
public OtherStep(FeatureContextDriver featureContextDriver)
{
_featureContextDriver = featureContextDriver;
}
public void ExecuteStep()
{
_featureContextDriver.FeatureContextChanging(this.FeatureContext);
}
}
Run Code Online (Sandbox Code Playgroud)
代码未经测试/试用并应用驱动程序模式。
全面披露:我是 SpecFlow 和 SpecFlow+ 的维护者之一。