How to read test run settings parameter value in s

2020-05-09 06:46发布

问题:

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

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.'"

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

This code worked fine while using it in the Microsoft Unit Test project. How to read values from Test Run Settings file for specflow tests? Is there any other way to access runsettings parameters?

回答1:

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

You can get it via DI:

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

Complete example: https://github.com/techtalk/SpecFlow/blob/master/Tests/TechTalk.SpecFlow.Specs/Features/MsTestProvider.feature#L43

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