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

  • 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