【问题标题】:Specflow Container of the steps class has not been initialized步骤类的 Specflow 容器尚未初始化
【发布时间】:2017-11-08 08:33:09
【问题描述】:
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);
    }
}

这是一个示例 sn-p。当我尝试访问 this.FeatureContext.Add() 时,我收到一个异常声明 Container of the steps class has not been initialized

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

【问题讨论】:

    标签: c# specflow xunit


    【解决方案1】:

    FeatureContext 没有初始化,因为 Step 类没有被 SpecFlow DI Container 解析。所以没有调用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
    }
    

    您的代码可能如下所示:

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

    代码未经测试/试用并应用驱动模式。


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多