SpecFlow - Hooks



Hooks are event bindings to add more automation logic at certain steps. For example, for any step which is needed to be run prior to a specific Scenario. To introduce, hooks in the code we have to add the [Binding] attribute.

Hooks have global access. But it can be made available to a Features and Scenarios by declaring a scoped binding. The scoped binding can be filtered with the tags.

SpecFlow+ Runner Limitations

If we are executing tests from more than one thread with SpecFlow+ Runner, the After and Before hooks like the BeforeTestRun and AfterTestRun are run only once for each thread.

Hook Attributes

The Hook attributes are listed below −

BeforeTestRun/AfterTestRun − This is used to run an automation logic prior/post to the complete test execution. The method it is applicable to should be static.

BeforeFeature/AfterFeature − This is used to run an automation logic prior/post to individual Feature execution. The method it is applicable to should be static.

BeforeScenario or Before/AfterScenario or After − This is used to run an automation logic prior/post to individual Scenario or Scenario Outline execution.

BeforeScenarioBlock/AfterScenarioBlock − This is used to run an automation logic prior/post to individual Scenario block execution. (in between the When and Given steps).

BeforeStep/AfterStep − This is used to run an automation logic prior/post to individual Scenario step execution.

Hook Execution Sequence

The hooks of similar type, for example two AfterScenario hooks, are run in a random sequence. To make execution in a specific sequence, we have to add the Order property in the hook attribute.

Example

[AfterScenario(Order = 1)]
public void CloseBrowser() {
   // we require this method to execute first...
}
[AfterScenario(Order = 2)]
public void VerifySessionIdAfterBrowserClose() {
   // ...so we require this method to execute after the CloseBrowser //method is run
}

The number signifies order which means that the hook with the lowest number is run first. If the number is omitted, the default value is 10000. It is not a good practise to depend on it and rather mention the order for individual hooks.

Also, if an unhandled exception is thrown, all the following hooks of similar type will be skipped. In order to prevent that, we should handle all the exceptions.

Advertisements