Open Source.NET

NSpec Simplifies Unit Testing

NSpec is a no-nonsense BDD framework for the .NET Framework, influenced by RSpec and leveraging NUnit assertions.

In the world of .NET unit testing, there are many choices.  Many times they are copies or ports of a framework originally designed in another language/platform. Each new iteration or project adds their own flavor and conventions in order to build a better tool. NSpec, a behavior-driven development (BDD) framework for .NET written by Amir Rajan and Matt Florence, is no exception.

However, NSpec works very hard to eliminate a lot of the ceremony usually associated with unit testing .NET code. There are neither attributes for test classes nor tests, instead opting for derivation from the NSpec.nspec class. Furthermore, test classes and test methods don't have to be public. This is a deviation from the majority of test frameworks. Since the default access modifier is private, this modifier can be omitted entirely. The result is a very clear-cut syntax without the ceremony usually associated with writing tests.

You can start using NSpec with your projects quickly. First, install NSpec for your project via NuGet:

  >Install-Package nspec

Next, create a set of example specs and a simple class to test:

  using NSpec;

  namespace NSpec.Examples
  {
    class StackSpecs : nspec
    {
      Stack stack;
  
      void given_a_new_stack()
      {
        before = () => stack = new Stack();
        it["should be empty"] = () => stack.IsEmpty.is_true();
        it["should have a count of 0"] = () => stack.Count.should_be( 0 );
        it["Peeking should return null"] = () => stack.Peek().should_be( default(int) );
        context["When an item has been pushed into the stack"] =
            () =>
            {
              before = () => stack.Push( 5 );
              it["The count should have increased by 1"] = () => stack.Count.should_be( 1 );
              it["The stack should not be empty"] = () => stack.IsEmpty.should_be_false();
              it["Peeking should return the added value"] = () => stack.Peek().should_be( 5 );
            };
      }

      void given_a_stack_with_a_single_item()
      {
        before = () =>
             {
               stack = new Stack();
               stack.Push( 5 );
             };

        context["Popping the stack with one item"] =
            () =>
            {
              before = () => stack.Pop();

              it["Popping should make the stack empty"] =
                  () => stack.IsEmpty.should_be_true();
              it["Popping should make count 0"] =
                  () => stack.Count.should_be( 0 );
            };
        context["When another item has been pushed into the stack"] =
            () =>
            {
              before = () => stack.Push( 1 );
              it["The count should have increased by 1"] = () => stack.Count.should_be( 2 );
              it["Peeking should return the added value"] = () => stack.Peek().should_be( 1 );
            };
      }
    }

    public class Stack
    {
      private readonly System.Collections.Generic.List _Items =
        new System.Collections.Generic.List();

      public bool IsEmpty { get { return Count == 0; } }

      public int Count { get { return _Items.Count; } }

      public T Peek()
      {
        return IsEmpty ? default(T) : _Items[_Items.Count - 1];
      }

      public void Push(T value)
      {
        _Items.Add( value );
      }

      public T Pop()
      {
        T last = _Items[_Items.Count - 1];
        _Items.RemoveAt( _Items.Count - 1 );
        return last;
      }
    }
  }

Finally, the specs are run on the command line, telling our testing story.

C:\Dev\NSpec.Examples> .\packages\nspec.0.9.51\tools\NSpecRunner.exe .\NSpec.Examples\bin\Debug\NSpec.Examples.dll

StackSpecs
  given a new stack
    should be empty
    should have a count of 0
    Peeking should return null
    When an item has been pushed into the stack
      The count should have increased by 1
      The stack should not be empty
      Peeking should return the added value
  given a stack with a single item
    Popping the stack with one item
      Popping should make the stack empty
      Popping should make count 0
    When another item has been pushed into the stack
      The count should have increased by 1
      Peeking should return the added value

10 Examples, 0 Failed, 0 Pending

Speed and feedback are valuable features in a test framework; and the tests run very fast, giving instant feedback. In addition to the rate at which I get feedback, I want to know what failed. Typically, when many assertions are made in a single test method, the intent is lost and the test must be interpreted to determine the failure. NSpec delivers a very descriptive error message so that I can know exactly what failed. The burden is on the developer to write the appropriate tests, but it's well worth it when identifying failures.

  given a stack with a single item
    When another item has been pushed into the stack
      The count should have increased by 1
      Peeking should return the added value - FAILED - Expected: 2, But was: 1

**** FAILURES ****

nspec. StackSpecs. given a stack with a single item. When another item has been pushed into the stack. 
Peeking should return the added value. Expected: 2, But was: 1 at NSpec.Examples.Stack.b__11()
in C:\Dev\NSpec.Examples\NSpec.Examples\StackSpecs.cs:line 48 1 Examples, 1 Failed, 0 Pending

This sample only covers a subset of features available in NSpec. The NSpec Web site has a great walkthrough covering several testing scenarios. I prefer not to run my specs by hand, opting for NSpec's continuous testing counterpart, SpecWatchr, which I covered in Continuous Testing: Think Different.

NSpec's terse syntax reduces the amount of typing, and allows many tests to be written in only a few lines of code. Fast runtime reduces my feedback loop, allowing me to write better-tested and faster code.

About the Author

Ian Davis is the Master Code Ninja for software architecture and development consulting firm IntelliTechture. A C# MVP, Davis is an expert on the .NET Tramework and co-organizer of the Spokane .NET User Group who frequently speaks at industry events. He spends most of his free time as an open source author and advocate, publishing and working on many open source projects.

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