Behavior-Driven Development Using SpecFlow
As software development becomes complicated, writing unit tests provides a protection against constant changes and modifications. Traditionally, unit tests were written by testing each piece of the application layer in isolation. With the advent of behavior-driven development, now our unit tests can be composed into user defined stories. Each story represents a single feature of the application which can be tested from end to end. This method makes sure that the unit test only passes when the story is completely done. In this article I’ll show you how to use SpecFlow and WatiN to write BDD-style tests to implement user stories.
SpecFlow is inspired by Cucumber framework in the Ruby on Rails world. Cucumber uses plain English in the Gherkin format to express user stories. Once the user stories and their expectations are written, the Cucumber gem is used to execute those stores. SpecFlow brings the same concept to the .NET world and allows the developer to express the feature in plain English language.
You can download the SpecFlow framework from the official website, specflow.org. The installation files also install the Visual Studio template for SpecFlow which you can use when writing user stories.
Scenario and Setup
In this article I’ll show you how to implement the user registration feature, which is a common feature implemented on most of the websites.
The solution comprises of two different projects. One project is an ASP.NET MVC project and the other one is a Microsoft Unit Test project. Before we start writing our features we need to add the SpecFlow framework to your test project. You can accomplish this in different ways but the easiest method is to use NuGet to download and reference the SpecFlow libraries. From within the Visual Studio launch the Package Manager Console and issue the “Install-Package SpecFlow” command as shown below in Figure 1:
Figure 1: NuGet Package Manager Console.
Make sure that the Default project in Package Manager Console is setup as the MS Test project and not the web application project. Issuing the above command will add a SpecFlow reference to the test project. Repeat the same procedure for installing the WatiN framework which will be used to automate the user interface. After installing the SpecFlow and WatiN, we are ready to write some BDD-style unit tests.