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

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube