NExpect

An assertions framework for .NET with a BDD-like feel, inspired by Chai and Jasmine, designed to be user-extensible

View on GitHub

About a year or so ago, I discovered AssertionHelper, a base class provided by NUnit which allowed for a more familiar style of testing when one has to bounce back and forth between (Java|Type)Script and C#. Basically, it allows one to use the Expect keyword to start an assertion, eg:

[TestFixture]
public class TestSystem: AssertionHelper
{
  [Test]
  public void TestSomething()
  {
    Expect(true, Is.True);
  }
}

And, for a while, that sufficed. But there were some aspects of this which bothered me:

A few months after I started using it, a bigger bother arrived: the NUnit team was deprecating AssertionHelper because they didn’t think that it was used enough in the community to warrant maintenance. A healthy discussion ensued, wherein I offered to maintain AssertionHelper and, whilst no-one objected, the discussion seemed to be moth-balled a little (things may have changed by now). Nevertheless, my code still spewed warnings and I hate warnings. I suppressed them for a while with R# comments and #pragma, but I couldn’t deal – I kept seeing them creep back in again with new test fixtures.

This led me to the first-pass: NUnit.StaticExpect where I’d realised that the existing AssertionHelper syntax could be accomplished via

This meant that the code above could become:

using static NUnit.StaticExpect.Expectations;

[TestFixture]
public class TestSystem
{
  [Test]
  public void TestSomething()
  {
    Expect(true, Is.True);
  }
}

Which was better in that:

But there was still that odd future-present tense mix. So I started hacking about on NExpect

NExpect states as its primary goals that it wants to be:

expect(result).toBeAFrobNozzle();

Which also negated well:

expect(result).not.toBeAFrobNozzle();

In NExpect, you can write an extension method FrobNozzle(), dangling off of IA<T>, and write something like:

Expect(result).To.Be.A.FrobNozzle();<br />
// or, negated<br />
Expect(result).Not.To.Be.A.FrobNozzle();<br />
// or, negated alternative<br />
Expect(result).To.Not.Be.A.FrobNozzle();

The result is something which is still evolving, but is already quite powerful and useful – and trivial to extend. I suggest checking out the demo project I made showing the evolution 

For the best effect, clone the project, reset back to the first commit and “play through” the commits.

NExpect has extensibility inspired by Jasmine and a syntax inspired by Chai (which is a little more “dotty” than Jasmine).

I’ve also had some great contributions from Cobus Smit, a co-worker at my ex-employer Chillisoft who has not only helped with extending the NExpect language, but also through trial-by-fire usage in his own project.