Access TestContext in SpecFlow Step Binding class

元气小坏坏 提交于 2019-12-06 00:35:12

I found a way to pass parameters to TestContext and then access them from SpecFlow.

By adding a [TestClass] which has a TestContext property and marking its AssemblyInit() method as [AssemblyInitialize] so it gets initialized early before runnig the tests and MSTest will be able to populate the TestContext.

{
    [TestClass]
    public class InitializeTestContext
    {
        public static TestContext Context { get; private set; }

        [AssemblyInitialize]
        public static void AssemblyInit(TestContext context)
        {
            Context = context;
        }
    }
}

And then can access it from my BaseSteps class:

{
            public abstract class BaseSteps : TechTalk.SpecFlow.Steps
            {
                public string GetTestEnvironment()
                {
                    TestContext testContext = InitializeTestContext.Context;

                    string testEnvironment = testContext.Properties["Environment"].ToString();

                    return testEnvironment;
                }
            }
}

Gáspár Nagy answered on SpecFlow google group: https://groups.google.com/group/specflow/browse_thread/thread/5b038e3e283fdbfe#

By default not. We have a test-provider independent ScenarioContext.Current that can be used for similar purposes.

Further to Valentin's answer. Here is an example of a test generator that will add in the test context. Its from the same Google group.

Gáspár Nagy said it may be added to the provider that ships in specflow.

So to answer the OP's question, yes it is possible.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!