使用SpecFlow + SpecRunner时在线程之间共享数据

问题描述 投票:1回答:2

我正在开发一个使用SpecFlow + SpecRunner和XUnit的测试套件实现。我们正在尝试进行并行测试执行,我想知道是否有一种方法可以在测试运行开始时运行钩子并将令牌值存储在静态变量中,以便可以在线程之间共享。

总结一下,specflow提供了一种在并行执行期间在线程之间共享数据的机制。

c# specflow
2个回答
1
投票

您可以使用上下文注入在并行执行期间共享数据。这可以允许线程之间共享状态。

[Binding]
public class MyScenario
{
    private readonly ScenarioContext scenarioContext;

    public MyScenario(ScenarioContext scenarioContext)
    {
        this.scenarioContext = scenarioContext;
    }

    [Given(@"I put something in the shared context")]
    public void GivenIPutSomethingInTheSharedContext()
    {
        //Add to scenarioContext
    }

    [Given(@"I read something in the shared context")]
    public void GivenIReadSomethingInTheSharedContext()
    {
        //Get from scenarioContext
    }
}

-1
投票

我们可以使用以下任何一种方法共享数据

  1. 场景背景
  2. 上下文注入

这里,方法1和方法2在多线程中不会有任何问题。因为,上下文注入生命特定于场景级别。

方法1:我们可以在BeforeScenario钩子中定义令牌生成步骤,并且可以在ScenarioContext中更新生成的令牌值。

我们可以在下面的任何地方直接从场景上下文中访问令牌

在这里,Token将在每个场景运行之前生成,它不会影响并行执行。有关更多详细信息,请访问Parallel-Execution

场景及其相关的钩子(前/后场景,场景块,步骤)在执行期间在不同的线程中被隔离,并且不会相互阻塞。每个线程都有一个单独的(和隔离的)ScenarioContext。

钩类:

public class CommonHooks
{
    [BeforeScenario]
    public static void Setup()
    {
        // Add Token Generation Step
        var adminToken = "<Generated Token>";
        ScenarioContext.Current["Token"] = adminToken;
    }
}

步骤类:

[Given(@"I Get the customer details""(.*)""")]
public void WhenIGetTheCustomerDetails(string endpoint)
{
   if(ScenarioContext.Current.ContainsKey("Token"))
   {
       var token = ScenarioContext.Current["Token"].ToString();
       //Now the Token variable holds the token value from the scenario context and It can be used in the subsequent steps
   }
   else
    {
        Assert.Fail("Unable to get the Token from the Scenario Context");
    }
}

如果您希望在多个Step中共享相同的标记,则可以在构造函数中分配此标记值,并且可以使用它

例如,

[Binding]
public class CustomerManagementSteps
{
    public readonly string token;
    public CustomerManagementSteps()
    {
        token= ScenarioContext.Current["Token"].ToString();
    }

    [Given(@"I Get the customer details""(.*)""")]
    public void WhenIGetTheCustomerDetails(string endpoint)
    {
        //Now the Token variable holds the token value from the scenario context and It can be used in the subsequent steps       
    }
}

方法2:上下文注入细节可以在下面的链接中参考一个例子

Context Injection

© www.soinside.com 2019 - 2024. All rights reserved.