Alexander Beletsky's development blog

My profession is engineering

Clean tests with SharpTestsEx

I was recently been adding NUnit to one of mine project’s and noticed one interesting framework in Nuget channel. It is SharpTestsEx by Fabio Maulo and its primary goal is to make your assertions shorter, cleaner and easy to read.

To start with, it is just enough to install it through Nuget (or manually) and add using statement in your test class file.

using SharpTestsEx;

SharpTestsEx would add number of Should() extension methods. Suppose you have such case:

[Test]
public void Compile_Div_EmptyDivElement()
{
    // arrange
    var compiler = new Compiler();

    // act
    var result = compiler.Compile("div");

    // assert
    Assert.That(result, Is.Equal("<div></div>"), "expected and actual results are different");
}

With SharpTestsEx I’m changing assert part of test to,

[Test]
public void Compile_Div_EmptyDivElement()
{
    // arrange
    var compiler = new Compiler();

    // act
    var result = compiler.Compile("div");

    // assert
    result.Should().Be.EqualTo("<div></div>");
}

Note, it is much shorter and mostly plain English sentence: result should be equal to something.. The assertion message for this test is really clean and sufficient, so you mostly won’t needed and custom messages.

If I go further and implement extension method for this Compile method:

static class CompilerTestExtension
{
    public static string Compile(this string expression)
    {
        var c = new Compiler();
        return с.Compile(expression);
    }
}

My tests case would be just one line of code:

[Test]
public void Compile_Div_EmptyDivElement()
{
    // arrange / act / assert
    "div".Compile().Should().Be.EqualTo("<div></div>");
}

This is very short and clean notation of test case, even not technical person could read this. You can do more complicated assertions, combining them by And / Not conditions. There are also bunch of useful extensions for strings, sequences.

Additional information on project site as well as author blog.