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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube