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

  • VS Code v1.99 Is All About Copilot Chat AI, Including Agent Mode

    Agent Mode provides an autonomous editing experience where Copilot plans and executes tasks to fulfill requests. It determines relevant files, applies code changes, suggests terminal commands, and iterates to resolve issues, all while keeping users in control to review and confirm actions.

  • Windows Community Toolkit v8.2 Adds Native AOT Support

    Microsoft shipped Windows Community Toolkit v8.2, an incremental update to the open-source collection of helper functions and other resources designed to simplify the development of Windows applications. The main new feature is support for native ahead-of-time (AOT) compilation.

  • New 'Visual Studio Hub' 1-Stop-Shop for GitHub Copilot Resources, More

    Unsurprisingly, GitHub Copilot resources are front-and-center in Microsoft's new Visual Studio Hub, a one-stop-shop for all things concerning your favorite IDE.

  • Mastering Blazor Authentication and Authorization

    At the Visual Studio Live! @ Microsoft HQ developer conference set for August, Rockford Lhotka will explain the ins and outs of authentication across Blazor Server, WebAssembly, and .NET MAUI Hybrid apps, and show how to use identity and claims to customize application behavior through fine-grained authorization.

  • Linear Support Vector Regression from Scratch Using C# with Evolutionary Training

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the linear support vector regression (linear SVR) technique, where the goal is to predict a single numeric value. A linear SVR model uses an unusual error/loss function and cannot be trained using standard simple techniques, and so evolutionary optimization training is used.

Subscribe on YouTube