NUnit 2.4+ constraint-based assertion syntax

NUnit has moved to a constraint-based assertion syntax in the last release, which allows constraints to be specified in semi-natural language.

For example, the classic style of asserting equality was:

  Assert.AreEqual(expectedValue, actualValue);

Using constraint-based syntax, this becomes:

  Assert.That(actualValue, Is.EqualTo(expectedValue));

This is a bit more natural to read and write, and makes it quite explicit which value is being checked in the assertion and which is the expected value. This syntax is also very flexible, and allows you to create some really interesting constraints. NUnit provides a number of syntax helpers to make writing these very easy. These syntax handlers are basically factories for a number of classes that implement IConstraint. In the example above, Is is the syntax helper, and Is.EqualTo(object) is a factory method that creates an EqualConstraint object.

I always forget these syntax handler shortcuts, and end up referring to a post from Charlie about NUnit 2.4 RC2, or using Reflector. So here is a summary for my future reference (so I can bug myself instead of the NUnit blog :-)).

  • Has: Check object properties (property value and length).
  • Is: the main helper. Can check for equality, null, true/false, type, comparisons and more.
  • List: Can check if a list contains an specific object.
  • Text: Various string-based constraints.

SyntaxHelper classes also have some other useful properties, such as Not, All, Some, that can be used for negation and collections. You can also use the !, &, and | operators to negate, AND, and OR constraints together.

Finally, there are some constraint modifiers like AsCollection, IgnoreCase and Within(tolerance) attached to some constraint types that are quite cool.

Comments