Access TestContext in SpecFlow Step Binding class

点点圈 提交于 2019-12-07 13:48:39

问题


Is it possible to access the MSTest TestContext from within a SpecFlow (1.7.1) step binding class? In the generated code of a feature file there is a method FeatureSetup which takes the TestContext as an argument but apparently doesn't do anything with it.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7334452/access-testcontext-in-specflow-step-binding-class

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