Practical ASP.NET

SpecFlow Two-Step Parameter Conversions

Here's how to use SpecFlow to convert plain-text scenario steps into .NET types.

SpecFlow allows the building of a bridge between the business and the development team by allowing the creation of business-readable tests. It does this by allowing the writing of high-level scenarios written in natural language (English, French, German and so on).

A scenario consists of a number of steps and steps can contain parameters. Parameterized steps allow the re-use of step code and reduce test code duplication. For example, if you wanted to write some test code to set up when a password was last changed, a parameterized step definition could be created, as shown here:.

[Given(@"I last changed my password (.*) days ago")]
public void GivenMyPasswordWasCreatedOverDaysAgo(int daysSincePasswordChanged)
{            
}

This parameterized step definition can now be called from multiple scenarios and different values for the number of days to be specified:

Given I last changed my password 30 days ago
Given I last changed my password 10 days ago
Given I last changed my password 366 days ago

Automatic Step Value Conversion
SpecFlow can automatically convert the plain text in the scenario steps into .NET types. Basic conversions are supported such as conversions to integers, conversions to enum values and conversions to Guids. Listing 1 shows three step definitions that take advantage of this automated step parameter conversion.

Listing 1: Parameterized Steps with Automatically Converted Parameter Types
[Given(@"Step with basic conversion of int (.*)")]
public void GivenStepWithBasicConversionOfInt(int i)
{            
}

[When(@"Step with enum conversion of (.*)")]
public void WhenStepWithEnumConversionOfEnum(ConsoleColor color)
{            
}

[Then(@"Step with GUID conversion of (.*)")]
public void ThenStepWithGUIDConversion(Guid g)
{            
}

Here's an example step text that matches that listing:

Scenario: Built in Conversions
   Given Step with basic conversion of int 42
   When Step with enum conversion of DarkMagenta
   Then Step with GUID conversion of E6E4174C-B00E-4890-962D-7789B12472F7

Custom Conversions
In addition to automatically converted values, SpecFlow is extensible and allows custom conversions to be created. For example, the step text, "Given I last changed my password 30 days ago," could map to a DateTime parameter in the step definition. Out of the box, SpecFlow doesn't know how to convert from the string "30 days ago" into an instance of a .NET DateTime. Here's a scenario that might make use of this type of custom conversion:

Scenario: Force password update if current password is too old
  Given I last changed my password 30 days ago
  When I log in successfully
  Then I should be asked to enter a new password

In the matching step definition, the type of the parameter value is of DateTime:

[Given(@"I last changed my password (.* days ago)")]
public void GivenMyPasswordWasCreatedOverDaysAgo(DateTime passwordLastChanged)
{            
}

If this scenario were executed, it would fail with an error: "The string was not recognized as a valid DateTime."

To create a custom conversion from the text "n days ago" to a DateTime, the [StepArgumentTransformation] attribute can be applied to a method that will be automatically called to perform the conversion. The method that has this attribute applied must be inside a class that is marked with the SpecFlow [Binding] attribute. Listing 2 shows an example of a new class that has the [Binding] attribute applied and a method called DaysAgoTransform that will be invoked. 

Listing 2: A Custom Transform That Returns a DateTime
using System;
using TechTalk.SpecFlow;

namespace SpecFlowHooks
{
  [Binding]
  public class CustomTransforms
  {
    [StepArgumentTransformation(@"(\d+) days ago")]
    public DateTime DaysAgoTransform(int daysAgo)
    {
      return DateTime.Today.AddDays(-daysAgo);
    }
  }
}

Notice that the [StepArgumentTransformation] has a parameter to say when this conversion should be invoked, in this example when the original step text matches the regular expression "(\d+) days ago."

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