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

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube