如何在 specflow 测试中读取测试 运行 设置参数值?

How to read test run settings parameter value in specflow tests?

我们使用 visual studio 中的 .运行settings 文件进行 运行ning specflow 测试。我们在那里配置了某些参数。我需要在 运行 时间访问这些参数值以在 specflow 测试方法中使用。我尝试通过 TestContext 访问那些,如下所示

 [ClassInitialize]
    public static void Initialize(TestContext testContext)
        {            
            var value= 
            Convert.ToString(testContext.Properties["testParameter1"]);
        }

我在 运行 时间收到 testcontext 实例的异常,如下所示。 "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

环境 Visual Studio 企业 2017 规格流 2.2.1 单元测试提供商:MsTest

这段代码在 Microsoft 单元测试项目中使用时运行良好。如何从 Specflow 测试的测试 运行 设置文件中读取值?还有其他方法可以访问 运行 设置参数吗?

因为它们在 TestContext 上,所以您需要它的实例。

你可以通过DI获取:

[When(@"I do something")]
public void WhenIDoSomething()
{
    var textContext = ScenarioContext.Current.ScenarioContainer.Resolve<Microsoft.VisualStudio.TestTools.UnitTesting.TestContext>();
}

完整示例:https://github.com/techtalk/SpecFlow/blob/master/Tests/TechTalk.SpecFlow.Specs/Features/MsTestProvider.feature#L43

但请注意,它目前在 BeforeScenario 挂钩中不起作用 (https://github.com/techtalk/SpecFlow/issues/936)