These are block codes that run before and after each scenario, between each step definitions, before and after each scenario block , before and after test run in the feature file. This permits us to deal with the code work process better and assists with decreasing code excess.
Hooks can be characterized anyplace in the task or step definition layers utilizing the strategies [Before] and [After]. They are typically used for setup and tear-down of the environment then after the fact every situation.
Where we need Hooks -
Hooks are often wont to perform background tasks that aren't a part of business functionality. Such tasks could be before the test and after a test like
- Starting up a browser
- Setting or clearing cookies
- Connecting to a database
- Checking the state of the system
- Monitoring
- Navigating to certain page
- Logging out from the application
Before scenario - It will run before each scenario
Syntax: [BeforeScenario] or [Before]
After scenario - It will run after each scenario
Syntax: [AfterScenario] or [After]
[Before] - Before hooks run before every scenario. This is often commonly used for prerequisite steps that require to be performed before the particular test scenario. For instance , this will be as follows.
1. Initialize a web driver
2. Establish DB connections
3. To set up test data
4. To set browser cookies
5. Navigate to default page
[After] - It starts execution after the last stage of the scenario.
1. Quit the web driver
2. To close DB connections
3. To clear the test data/browser cookies
4. Sign out from the application
5. Take screenshots for fail/pass scenarios
Before Step - It will run before each step
Syntax: [BeforeStep]
After step - It will run after each step
Syntax: [AfterStep]
To run before/after executing each scenario block (e.g. between the "givens" and the "whens")
Feature Hook will run before/after executing each feature and the method should be static.
Before Test Run and after Test Run is used and the method should be static.
Hooks.cs