如何在Specflow测试中读取测试运行设置参数值? [英] How to read test run settings parameter value in specflow tests?

查看:281
本文介绍了如何在Specflow测试中读取测试运行设置参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在Visual Studio中使用.runsettings文件来运行specflow测试.在那里,我们配置了某些参数.我需要在运行时访问这些参数值,以在specflow测试方法中使用.我尝试通过TestContext如下访问那些

We use .runsettings file in visual studio for running specflow tests. There we have certain parameters configured. I need to access those parameter values at run time to use in specflow test methods. I tried accessing those via TestContext as below

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

我在运行时遇到testcontext实例的异常,如下所示. "System.NullReferenceException:'对象引用未设置为对象的实例.'

I am getting the exception for testcontext instance at run time as below. "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

环境 Visual Studio企业版2017 Specflow 2.2.1 单元测试提供者:MsTest

Environment Visual Studio Enterprise 2017 Specflow 2.2.1 Unit Test Provider: MsTest

在Microsoft单元测试项目中使用此代码时,它可以正常工作.如何从Specflow测试的测试运行设置"文件中读取值?还有其他方法可以访问运行设置参数吗?

推荐答案

就像它们在TestContext上一样,您需要它的实例.

As they are on the TestContext, you need the instance of it.

您可以通过DI来获取它:

You can get it via 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 )

But be aware, that it currently doesn't work in a BeforeScenario hook (https://github.com/techtalk/SpecFlow/issues/936)

这篇关于如何在Specflow测试中读取测试运行设置参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆