You’re probably familiar with the unit-testing framework NUnit, the .NET variant of the original Java-based JUnit. Just in case you don’t do unit testing at all (and you should, of course!), here’s how NUnit can be used to implement a test:

public static class Calculator {

  public static int Add (int a, int b) {

    return a + b;







public class Tests {


  internal void AddTest1( ) {

    Assert.AreEqual(20 + 10, Calculator.Add(20, 10));



Using a test runner, a program that loads the assembly with the tests inside and executes all the methods marked with the attributes, you can now execute the tests against your implemented functionality. When a test fails, the Assert.AreEqual() method (or one of the other methods in the Assert class) throws an exception, and the test runner outputs information about the test that has failed and the exception it has caught.

For quite a while now, NUnit has had a fluent API in addition to the standard one. Here’s how you can rewrite the preceding test with that fluent API:


public void AddTest1f( ) {

  Assert.That(Calculator.Add(20, 10),

    Is.EqualTo(10 + 20));


The idea of fluent APIs is that the user of the API can chain together calls to various API functions. These APIs are quite hard to write because of the complex interactions that are possible between the return values and parameters of all the functions involved. Here are a few more examples:

public static class DataSource {

  public ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.