Practical ASP.NET

Run Additional Test Code with SpecFlow 2 Hooks

You know how to run business-readable tests. Let's continue with a few more hooks.

SpecFlow allows the building of a bridge between the business and the development team by allowing the creation of business readable tests. The business readable English (other spoken languages are supported) steps in the scenario map to step definition methods that contain the test automation code.

In addition to code contained in step definition methods, additional test code can be executed at various points during the test execution lifecycle. This code can perform additional environmental or other test setup and clean up code.

The following is an overview of where additional test execution code can be executed:

  • Before the entire test run
  • After the entire test run
  • Before any of the scenarios in a feature execute
  • After all of the scenarios in a feature have executed
  • Before each scenario is executed
  • After each scenario is executed
  • Before each logical scenario block (the logical Given, When and Then phases)
  • After each logical scenario block (the logical Given, When and Then phases)
  • Before each individual step in scenarios
  • After each individual step in scenarios

Hooks are created by applying a SpecFlow attribute to a method in a class that has the [Binding] attribute applied.

The available hook attributes are:

  • [BeforeTestRun]
  • [AfterTestRun]
  • [BeforeFeature]
  • [AfterFeature]
  • [BeforeScenario] (or [Before] for short)
  • [AfterScenario] (or [After] for short)
  • [BeforeScenarioBlock]
  • [AfterScenarioBlock]
  • [BeforeStep]
  • [AfterStep]

Hook methods can be added to the generated steps class or to a class that's created manually and that has the [Binding] attribute applied. Here's a simple feature that contains a scenario:

Feature: Calculator
  In order to make it easier on my brain
  As someone who is not good at mental arithmetic
  I want to use the computer to do basic maths

Scenario: Add two numbers
  Given The calculator is reset 	
  When I enter 40
    And I Add 20
  Then The value should be 60

The steps file for this feature contains the code shown in Listing 1. In this steps class the calculator is being created in the class, but this could be changed so that it's created before each scenario executes by using the [BeforeScenario] attribute.

Listing 1: Steps Class for Calculator Feature
using NUnit.Framework;
using TechTalk.SpecFlow;

namespace SpecFlow2Demo
{
  [Binding]
  public class CalculatorSteps
  {
    Calculator calculator = new Calculator();

    [Given]
    public void GivenTheCalculatorIsReset()
    {            
      calculator.Reset();
    }
        
    [When]
    public void WhenIEnter_VALUE(int value)
    {
      calculator.Value = value;
    }
        
    [When]
    public void WhenIAdd_NUMBERTOADD(int numberToAdd)
    {         
      calculator.Add(numberToAdd);
    }
        
    [Then]
    public void ThenTheValueShouldBe_EXPECTEDRESULT(int expectedResult)
    {
      Assert.That(calculator.Value, Is.EqualTo(expectedResult));
    }
  }
}

To add the before scenario hook, the following code can be added to the steps class and the instantiation of the calculator moved into the method:

private Calculator calculator;

[BeforeScenario]
public void SetupCalculator()
{
  Console.WriteLine("[BeforeScenario] - Creating new calculator");
  calculator = new Calculator();
}

To add hook methods outside of a steps class, create a new class and apply the [Binding] attribute as shown in Listing 2. Notice in this class that another [BeforeScenario] hook has been added.

Listing 2: Hook Methods in Additional Classes
using System;
using TechTalk.SpecFlow;

namespace SpecFlow2Demo
{
  [Binding]
  public class MyHooks
  {
    [BeforeScenario]
    public static void BeforeScenarioStarts()        
    {
      Console.WriteLine("[BeforeScenario] - MyHooks class");
    }
  }
}

If you execute the test run now, you can see the following output:

[BeforeScenario] - Creating new calculator
[BeforeScenario] - MyHooks class
Given The calculator is reset
-> done: CalculatorSteps.GivenTheCalculatorIsReset() (0.0s)
When I enter 40
-> done: CalculatorSteps.WhenIEnter_VALUE(40) (0.0s)
And I Add 20
-> done: CalculatorSteps.WhenIAdd_NUMBERTOADD(20) (0.0s)
Then The value should be 60
-> done: CalculatorSteps.ThenTheValueShouldBe_EXPECTEDRESULT(60) (0.0s)

Notice that there are 2 [BeforeScenario] hook methods executed.

Most of the hook attributes can add tag filtering; this is where the hook will only execute if a specific tag (or tags) has been set at the feature or scenario level. If the [BeforeScenario] in the MyHooks class is modified to [BeforeScenario("arts")] the method code will only execute if the "arts" tag is present. If you execute the test run now, you get the following output:

[BeforeScenario] - Creating new calculator
Given The calculator is reset
-> done: CalculatorSteps.GivenTheCalculatorIsReset() (0.0s)
When I enter 40
-> done: CalculatorSteps.WhenIEnter_VALUE(40) (0.0s)
And I Add 20
-> done: CalculatorSteps.WhenIAdd_NUMBERTOADD(20) (0.0s)
Then The value should be 60
-> done: CalculatorSteps.ThenTheValueShouldBe_EXPECTEDRESULT(60) (0.0s)

Notice that you no longer get "[BeforeScenario] - MyHooks class" in the output because there is no "arts" tag applied in the feature file.

About the Author

Jason Roberts is a Microsoft C# MVP with over 15 years experience. He writes a blog at http://dontcodetired.com, has produced numerous Pluralsight courses, and can be found on Twitter as @robertsjason.

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events