How to use MSTest Annotations in specflow c#?

Rest AssuredDynamic ProgrammingProgramming

We can use MSTest annotations in SpecFlow C# in hooks. Hooks are event bindings to add more automation logic at certain steps. For example, for any step which is needed to be run before 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 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 is 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.

  • BeforeFeature/AfterFeature - This is used to run an automation logic prior/post to individual Feature execution.

  • 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 a similar type, for example, two AfterScenario hooks, are run in a random sequence. To execute 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 a similar type will be skipped. To prevent that, we should handle all the exceptions.

raja
Updated on 18-Nov-2021 11:37:49

Advertisements