Monday, April 4, 2016

SpecFlow - Using Hooks in your Tests

Introduction


In a previous article we talked about how we can create tests with Selenium and SpecFlow.This article explains how we can use Hooks to run our tests.


What are Hooks


Hooks = event bindings and can be used to perform additional automation logic on specific events, like, for example, the execution of a scenario. To make an analogy, think about Setup and Teardown attributes from nunit framework.


Types of Hooks



The names are intuitive
- Beforetestrun and aftertestrun represents the code that will be executed before and after all tests
- Beforefeature and afterfeature represents the code that will be executed before and after every feature
- Beforescenario and afterscenarion represents the code that will be executed before and after every scenario inside a feature
- Beforescenarioblock and afterscnearioblock represents the code that will be executed before and after every scenario block
To be more precise, below you can see an example of a scenario with 3 blocks. The test will be executed before and after Given/When/Then blocks

- Beforescenariostep and afterscneariostep represents the code that will be executed before and after every scenario step

Creating Hooks File


After you added the Spec Flow extension to your visual studio project, you are able to create a new item of type Hooks.



A default class is created:



Modify this class and add all hooks you need.

Restrict Hook Execution with Tag Filtering


Another specflow feature is to restrict hook execution based on the tags you set to your scenarios. If you didn't know for a scenario you can add a tab. Based on this you group your tests when running them. In the image below, the scenario tags are @Login and @forgotPassword



The code below from you hook file will be executed for those scenarios tagged with @Login and @forgotPassword (when we are in if)




Want to lean more about BDD? Have a look on this book: BDD in Action: Behavior-driven development for the whole software lifecycle


Happy testing and... make it green, becomes a dream :).


No comments:

Post a Comment

Popular Posts