Specflow -Part6(Specflow Hooks)

We may come across a scenario where we need to execute code after/before a particular event like given below

  1. We want to create some folder where we can store screenshots/ logfile before starting the test
  2. We may want to log details of the scenario in a log file after executing each step 
  3. We want to know after each step if that step was successful and if not we want to take a screenshot as an evidence
  4. We want to clean up the database before/after each scenario/feature 
  5. We  may want to open/close browser for every scenario
Hooks help us to execute logic when a certain event occurs, let's check how
I will start with creating a new project called SeleniumHooks and added folders where we can keep our feature, feature definitions and hooks file


We will add a feature file and implement the steps

Feature: SpecFlowFeature1
 In order to avoid silly mistakes
 As a math idiot
 I want to be told the sum of two numbers

@mytag
Scenario: Add two numbers
 Given I have entered 50 into the calculator
 And I have entered 70 into the calculator
 When I press add
 Then the result should be 120 on the screen

[Binding]
    public class SpecFlowFeature1Steps
    {
        [Given(@"I have entered (.*) into the calculator")]
        public void GivenIHaveEnteredIntoTheCalculator(int p0)
        {
           
        }
        
        [When(@"I press add")]
        public void WhenIPressAdd()
        {
           
        }
        
        [Then(@"the result should be (.*) on the screen")]
        public void ThenTheResultShouldBeOnTheScreen(int p0)
        {
          
        }
    }

We have kept the step definitions as blank for now, we will add hooks file where we will add some code which will get executed automatically on a particular event

To add hooks file, add new item-->Specflow-->Specflow hooks file

[Binding]
    public sealed class Hooks1
    {
        // For additional details on SpecFlow hooks see http://go.specflow.org/doc-hooks
 
        [BeforeScenario]
        public void BeforeScenario()
        {
            //TODO: implement logic that has to run before executing each scenario
        }
 
        [AfterScenario]
        public void AfterScenario()
        {
            //TODO: implement logic that has to run after executing each scenario
        }
    }

This is the default hooks file which we can extend for our project

We will print the title of scenario in before scenario execution is started and after the execution is completed we will print the description of the feature.

[BeforeScenario]
        public void BeforeScenario()
        {
            var scenarioTitle = ScenarioContext.Current.ScenarioInfo.Title;
            Console.WriteLine($"BeforeScenario: Scenario Title--> {scenarioTitle}");
 
        }
 
        [AfterScenario]
        public void AfterScenario()
        {
 
            var scenarioDescription = FeatureContext.Current.FeatureInfo.Description;
            Console.WriteLine($"AfterScenario:Feature Description--> {scenarioDescription}");
 
        }

Run the test and you will get below output

BeforeScenario: Scenario Title--> Add two numbers
Given I have entered 50 into the calculator
-> done: SpecFlowFeature1Steps.GivenIHaveEnteredIntoTheCalculator(50) (0.0s)
And I have entered 70 into the calculator
-> done: SpecFlowFeature1Steps.GivenIHaveEnteredIntoTheCalculator(70) (0.0s)
When I press add
-> done: SpecFlowFeature1Steps.WhenIPressAdd() (0.0s)
Then the result should be 120 on the screen
-> done: SpecFlowFeature1Steps.ThenTheResultShouldBeOnTheScreen(120) (0.0s)
AfterScenario:Feature Description--> In order to avoid silly mistakes
As a math idiot
I want to be told the sum of two numbers


Point to note here, BeforeScenario and AfterScenario methods are automatically called.
If we had multiple scenario's, these methods will be called before and after each scenario.

This way you can add your code for other events like BeforeTestRun, BeforeFeature BeforeStep etc

Now say, we have a scenario where, after a test step fails we want to take a screenshot of the browser.
We can add AfterStep hook which will check if the test run fails and then take a screenshot.

We will modify our Then step and purposefully fail that step to check if our code in AfterStep hook runs and take a screenshot.

Below modified step definition file

[Given(@"I have entered (.*) into the calculator")]
       public void GivenIHaveEnteredIntoTheCalculator(int p0)
       {
          
       }
       
       [When(@"I press add")]
       public void WhenIPressAdd()
       {
          
       }
       
       [Then(@"the result should be (.*) on the screen")]
       public void ThenTheResultShouldBeOnTheScreen(int p0)
       {
           throw new Exception("Failing the Step to check hook event");
         
       }

We will add AfterStep event to hooks file, modified hooks file below

[Binding]
    public sealed class Hooks1
    {
        // For additional details on SpecFlow hooks see http://go.specflow.org/doc-hooks
 
        [BeforeScenario]
        public void BeforeScenario()
        {
            var scenarioTitle = ScenarioContext.Current.ScenarioInfo.Title;
            Console.WriteLine($"BeforeScenario: Scenario Title--> {scenarioTitle}");
 
        }
 
        [AfterScenario]
        public void AfterScenario()
        {
 
            var scenarioDescription = FeatureContext.Current.FeatureInfo.Description;
           Console.WriteLine($"AfterScenario:Feature Description-->{scenarioDescription}");
 
        }
 
        [AfterStep]
        public void AfterStep()
        {
            //If test error then stepResult will be true
            bool stepResult = ScenarioContext.Current.TestError != null ? true : false;
 
            if(stepResult)
            {
                Console.WriteLine($"There was error executing Step: " +
                    $"{ScenarioStepContext.Current.StepInfo.Text}");
 
                Console.WriteLine($"Error Details: " +
                    $"{ScenarioContext.Current.TestError.Message}");
 
            }
 
        }
    }

Now when we run the test, Then step code will throw an exception and test will fail, In AfterStep method stepResult variable will be true and we will print the error details on screen and we can even add code to take a screenshot of web page here.

Run the test and you will get below output

BeforeScenario: Scenario Title--> Add two numbers
Given I have entered 50 into the calculator
-> done: SpecFlowFeature1Steps.GivenIHaveEnteredIntoTheCalculator(50) (0.0s)
And I have entered 70 into the calculator
-> done: SpecFlowFeature1Steps.GivenIHaveEnteredIntoTheCalculator(70) (0.0s)
When I press add
-> done: SpecFlowFeature1Steps.WhenIPressAdd() (0.0s)
Then the result should be 120 on the screen
-> error: Failing the Step to check hook event
There was error executing Step: the result should be 120 on the screen
Error Details: Failing the Step to check hook event
AfterScenario:Feature Description--> In order to avoid silly mistakes
As a math idiot
I want to be told the sum of two numbers






Comments

Popular posts from this blog

Specflow -Part3(Working with tables using Specflow.Assist.Dynamic)

Specflow -Part4(Specflow Scenario Outline and Feature Background )