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:

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?

About Johannes Brodwall

Johannes is Principal Software Engineer in SopraSteria. In his spare time he likes to coach teams and developers on better coding, collaboration, planning and product understanding.
This entry was posted in C#, Code, English, Unit testing. Bookmark the permalink.

3 Responses to Sweet C# test syntax

  1. 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.

  2. 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){
    toRoman(number) == roman

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

  3. 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.

Comments are closed.