【问题标题】:How to access an instance of a class created in a step from AfterScenario hook in SpecFlow?如何访问在 SpecFlow 中的 AfterScenario 挂钩的步骤中创建的类的实例?
【发布时间】:2018-09-20 08:08:33
【问题描述】:

我有一个名为“RollbackManager”的类,它用于从测试中添加一些操作并在测试后执行所有操作。

我使用 SpecFlow 进行测试,因此为了在测试后执行某些操作,我使用 [AfterScenario] 钩子。

问题是:当我并行运行测试时,我不能使RollbackManager 成为静态的!

问题是:如何从挂钩访问在 SpecFlow 步骤定义中创建的 RollBackManager 类的实例?

我目前的项目结构:

带有 RollbackManager 的基类:

public class StepBase : Steps
{
    public RollbackManager RollbackManager { get; } = new RollbackManager();

    protected new ScenarioContext ScenarioContext { get; set; }

    public StepBase(ScenarioContext scenarioContext)
    {
        RollbackManager = new RollbackManager();
    }
}

步骤定义类示例:

[Binding]
public sealed class ThenExport : StepBase
{
    public ThenExport(ScenarioContext scenarioContext) : base(scenarioContext)
    {
    }

    [Then(@"export status should contain entities: ""(.*)""")]
    public void ThenExportStatusShouldContain(List<String> commaSeparatedList)
    { 
        RollbackManager.RegisterRollback(() => Console.WriteLine());
    }
}

我的班级有钩子:

[Binding]
public sealed class SpecFlowTestsBase 
{

    [AfterScenario]
    public void AfterScenario()
    {
        // here I need my rollbacks craeted in steps
    }
}

【问题讨论】:

    标签: automated-tests ui-automation specflow


    【解决方案1】:

    首先,不要使用基本步骤类并将钩子放入其中。然后你的钩子会被执行多次。

    现在是你真正的问题:

    要在步骤类之间共享状态,您可以使用 SpecFlow 的上下文注入。
    绑定类的每个实例都将获得相同的 TestState 类实例。

    它是这样工作的:

    public class TestState
    {
        public RollbackManager RollbackManager { get; } = new RollbackManager();
    }
    
    [Binding]
    public sealed class ThenExport 
    {
        private TestState _testState;
    
        public ThenExport(TestState testState)
        {
            _testState = testState;
        }
    
        [Then(@"export status should contain entities: ""(.*)""")]
        public void ThenExportStatusShouldContain(List<String> commaSeparatedList)
        { 
            _testState.RollbackManager.RegisterRollback(() => Console.WriteLine());
        }
    }
    
    [Binding]
    public sealed class Hooks
    {
        private TestState _testState;
    
        public ThenExport(TestState testState)
        {
            _testState = testState;
        }
    
        [AfterScenario]
        public void AfterScenario()
        {
            _testState.RollBackManager.DoYourStuff();
        }
    }
    

    您可以在此处找到其他文档:
    https://specflow.org/documentation/Sharing-Data-between-Bindings/ https://specflow.org/documentation/Context-Injection/

    【讨论】:

    • 非常感谢,看来有帮助!我误解了使用上下文注入。谢谢你的例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    相关资源
    最近更新 更多