Specflow Hooks

Hooks allow you to execute code before and after scenarios. Consider below scenario. Now before executing below scenario, you want to start the browser and after execution is over, you have to close the browser.
Feature: Hooks Feature File

Scenario: Hook scenario
	Given I am on the yahoo website
	Then I verify that title is yahoo

Below is the step definition class for above feature file. Note that we have added BeforeScenario and AfterScenario Hooks. These methods would be automatically called before (to start browser)and after scenario (to close browser). If you want to hook BeforeScenario method to scenario tagged with say @sanity, you will have to use below syntax.

using System;
using TechTalk.SpecFlow;

namespace SpecFlowRunnerProject
    public class HooksFeatureFileSteps
        public void BeforeMethod()
            Console.WriteLine("Launch browser");

        [Given(@"I am on the yahoo website")]
        public void GivenIAmOnTheYahooWebsite()
            Console.WriteLine("I am on the yahoo website");
        [Then(@"I verify that title is yahoo")]
        public void ThenIVerifyThatTitleIsYahoo()
            Console.WriteLine("I verify title of yahoo website");

        public void AfterMethod()
            Console.WriteLine("Close browser");

Here is the output of above example. Note that before and after method were invoked.

Web development and Automation testing

solutions delivered!!