August 8, 2018

SpecFlow Basics

SpecFlow is hands down my favorite testing tool. I’ve been blogging about it since 2013 covering mostly advanced topics. In this post, I’ll go back to the beginning and briefly cover the basics to give you an idea of what it can do.

What is SpecFlow?

SpecFlow is a tool that allows you to:

  1. Define, manage, and automate human-readable acceptance tests in .NET.
  2. Enable BDD with easy to understand tests.
  3. Build up a living documentation of your system.

It consists of two parts: a Visual Studio extension and a runtime delivered via a NuGet package.

The Visual Studio extension is the design-time piece with:

  1. Gherkin syntax highlighting.
  2. File templates for features, hooks, and step definitions.
  3. Executable test generation (code-behind).

You use it to create your tests.

The NuGet package contains the runtime library which executes the tests generated by the Visual Studio extension. The SpecFlow runtime:

  1. Exposes meta-data about the current tests in the form of the scenario context, feature context, and test thread context.
  2. Loads a simple dependency injection framework.
  3. Provides table helper extension methods to make working with tables less painful.

Specify-Bind-Run

Once SpecFlow is installed, you’re ready to specify your first feature.

1
2
3
4
5
6
7
8
9
Feature: GoogleSearch
  In order to find information on the internet
  As a user of the Google search engine
  I want to perform a search

Scenario: Perform a Google Search
  Given a browser loaded with Google's web page
  When I search for "kittens"
  Then Google should return valid search results

Next you bind the Gherkins steps to executable code. Note the Binding attribute is applied to all binding classes. The Given, When, Then attributes bind to the individual Gherkin steps.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
[Binding]
public class GoogleSearch
{
    public GoogleSearch() { // Snip }

    [Given(@"a browser loaded with Google's web page")]
    public void LoadWebPage() { // Snip }

    [When(@"I search for (.*)")]
    public void Search(string searchTerm) { // Snip }

    [Then(@"Google should return valid search results")]
    public void ValidateSearchResults() { // Snip }
}

Finally you run the tests with a test runner. In this case, it’s NUnit.

1
nunit-console.exe /xml:results.xml some\path\tests.dll

Further Reading

For more details on getting started with SpecFlow, check out the excellent documentation. I recommend reading it once when getting started and again after you’ve had some experience. Also, check out my blog posts on SpecFlow.

© Joe Buschmann 2020