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?
Comments:
Thomas Ferris Nicolaisen - Feb 26, 2013
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” }
Jonas Follesø - Feb 26, 2013
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.
Alexander Esser - Feb 28, 2013
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.