Search code examples
bddspecflow

BeforeScenarioBlock to execute only before "Given" statement


Based on SpecFlow documentation, the [BeforeScenarioBlock] hook will be called before "Given" and "When" statement. Is there any way to make the [BeforeScenarioBlock] hook only to be called before "Given" statement ?


Solution

  • A [BeforeScenarioBlock] will run before any 'block' in the scenario, ie before each separate set of Given, When or Then blocks. There is no built in way to specify that a hook should only run before a particular type of block I don't think but I believe it should be straight forward enough to make sure that the code only runs before specific blocks inside the hook code. Something like this:

    [BeforeScenarioBlock]
    public void BeforeScenarioBlock()
    {
        if (ScenarioContext.Current.CurrentScenarioBlock == ScenarioBlock.Given)
        {
            //execute the code before the given
        }
    }
    

    Although I have not tested this.