Sweet C# test syntax

Two of my favorite libraries in C#: FluentAssertions and NUnit (of course). NUnit has a “hidden” gem (that is, it’s well documented, yet few developers use it): [TestCase]. Look at this:

using FluentAssertions;
using NUnit.Framework;
 
public class RomanNumeralsTest
{
    [TestCase(3333, "MMMCCCXXXIII")]
    [TestCase(555, "DLV")]
    [TestCase(999, "CMXCIX")]
    [TestCase(444, "CDXLIV")]
    public void ItConvertsNumbersToRomanNumerals(int number, string roman)
    {
        ToRoman(number).Should().Be(roman);
    }
}

The [TestCase] lets us easily have several test cases implemented by the same method. FluentAssertions adds the Should() extension method to all objects (and primitives, too) that let’s us write things like ToRoman(3333).Should().Be("MMMCCCXXXIII").

Add some sugar to your C# tests today. What’s your favorite ways of writing sweeter tests?

Creative Commons License
The Sweet C# test syntax by Johannes Brodwall, unless otherwise expressly stated, is licensed under a Creative Commons Attribution 3.0 Unported License.

About Johannes Brodwall

Johannes is a programmer with a small brain and a big ego. He thinks he can simplify most things, but he needs to dig down to understand them first.
This entry was posted in C#, Code, English, Unit testing. Bookmark the permalink.
  • http://twitter.com/follesoe Jonas Follesø

    Learning your standard test framework is often underestimated – many devs spend years in jUnit or NUnit, without taking time learning all its features.

    And I agree – FluentAsserts creates really nice, easy to read tests! I often use test-data builders for readable test data, and NSubstitue for a nice and easy mock framework.

  • http://www.tfnico.com Thomas Ferris Nicolaisen

    My current way of doing the same with Groovy & Spock (which is really sweet for a lot of reasons, especially mocking):

    def “Roman numerals”(int number, String roman){
    expect:
    toRoman(number) == roman

    where:
    number| roman
    3333 | “MMMCCCXXXIII”
    555 | “DLV”
    999 | “CMXCIX”
    444 | “CDXLIV”
    }

  • http://twitter.com/a3sser Alexander Esser

    Nice tip. The TestCase attribute is very useful when testing “low level” methods where a given input creates a defined output. It can lead to unreadable tests when used with methods where different parameter combinations have a different meaning. Using all those combinations in one test method isn’t a good idea. Those meanings should be expressed in different tests (with good names for the test methods).
    I often use the Assert.That(result, Is.EqualTo(expectedResult)) way when asserting results, but the FluentAssertions look interesting too.