Search code examples
c#nunitspecflowcontext-injection

C# Specflow - Need Feature and Scenario Title without using FeatureContext and ScenarioContext


I have a hooks.cs Binding file which have BeforeTestRun, BeforeFeature and BeforeScenario. I need Title of current Feature and scenario for log and report purposes. Since I am running the test in parallel, ScenarioContext throws exception as:

The ScenarioContext.Current static accessor cannot be used in multi-threaded execution...

Is there any way that I could get the current feature title and scenario title in multi-threaded execution?


Solution

  • Yes, you can get the current FeatureContext and ScenarioContext by getting it via constructor injection.

    public class MyBindingClass
    {
      private ScenarioContext scenarioContext;
    
      public MyBindingClass(ScenarioContext scenarioContext)
      {
        this.scenarioContext = scenarioContext;
      }
    
      [When("I say hello to ScenarioContext")]
      public void WhenISayHello()
      {
        // access scenarioContext here
      }
    }
    

    See https://specflow.org/documentation/ScenarioContext/ - Injecting ScenarioContext at the bottom.