Cover by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

NUNIT

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;

  }

}

 

...

 

[TestFixture]

public class Tests {

  [Test]

  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:

[Test]

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required