Creative use of closures in testing.

Having moved to Java, I do miss closures. xUnit.net has a creative use of closures in their unit testing framework:

[Test]
public void DivideByZeroThrowsException() {
  Assert.Throws<System.DivideByZeroException>(
    delegate {
      DivideNumbers(5, 0);
    });
}

This code snippet was taken from xUnit.net’s documentation.

Previously, each test method could have an expected exception. Now, one can have multiple calls which are expected to throw an exception in a single test method. Good thinking!

Written on October 14, 2007