尚未初始化步骤类的Specflow容器

时间:2017-06-07 06:24:44

标签: c# specflow xunit

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);
    }
}

这是一个示例代码段。当我尝试访问this.FeatureContext.Add()时,我收到一条说明Container of the steps class has not been initialized

的异常

对此有任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

FeatureContext未初始化,因为SpecFlow DI Container未解析Step类。因此不调用SetObjectContainer- Method(https://github.com/techtalk/SpecFlow/blob/master/TechTalk.SpecFlow/Steps.cs#L10

作为一般规则,您不应该自己实例化步骤类,而是通过Context Injection(http://specflow.org/documentation/Context-Injection/)获取它们。

但是在你的情况下这是不可能的,因为你在一个BeforeFeature钩子里。

一种可能的解决方案是,您使用最新的SpecFlow预发布版本(https://www.nuget.org/packages/SpecFlow/2.2.0-preview20170523)。 在那里,您可以通过钩子方法获取FeatureContext via参数。 看起来像这样:

[BeforeFeature]
public static void BeforeFeatureHook(FeatureContext featureContext)
{
    //your code
}

您的代码可能如下所示:

public class FeatureContextDriver
{
    public void FeatureContextChangeing(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.FeatureContextChangeing(featureContext);
    }
} 

[Binding]
public class OtherStep : Steps
{
    private FeatureContextDriver _featureContextDriver;
    public OtherStep(FeatureContextDriver featureContextDriver)
    {
        _featureContextDriver = featureContextDriver;
    }

    public void ExecuteStep() 
    {
        _featureContextDriver.FeatureContextChangeing(this.FeatureContext);
    }
}

代码未经过测试/试用并应用了驱动程序模式。

完全披露:我是SpecFlow和SpecFlow +的维护者之一。