The NUnit 3 documentation that introduces assertions and that compares the newer Constraint Model to the Classic Model includes the following example:
For example, the following code must use the constraint model. There
is no real classic equivalent.
int[] array = new int[] { 1, 2, 3 };
Assert.That(array, Has.Exactly(1).EqualTo(3));
Assert.That(array, Has.Exactly(2).GreaterThan(1));
Assert.That(array, Has.Exactly(3).LessThan(100));
While the document states that there is no "real classic equivalent," one could use Classic Syntax with LINQ to write what I would consider equivalent tests:
Assert.AreEqual(1, array.Where(x => x == 3).Count());
Assert.AreEqual(2, array.Where(x => x > 1).Count());
Assert.AreEqual(3, array.Where(x => x < 100).Count());
Some might conclude that the Constraint Model tests that I lifted from the documentation are more readable than these Classic Model equivalents. But that is arguably subjective.
However, that is not the whole story. More important is the improvement in the error message that a failed Constraint Model test emits when a test fails.† For instance, consider this Classic Model test that will fail:
int[] array = new int[] { 1, 2, 3 };
Assert.AreEqual(1, array.Where(x => x == 4).Count());
The AssertionException
that is thrown by NUnit contains the following "terse" Message
:
Expected: 1
But was: 0
In contrast, when expressing this test in the newer Constraint Model syntax:
Assert.That(array, Has.Exactly(1).EqualTo(4));
...NUnit returns the Message
:
Expected: exactly one item equal to 4
But was: < 1, 2, 3 >
I think that most would agree that this exception message is much more helpful than the one produced using NUnit's older Classic Model syntax.
† Much thanks to @nashwan for helping me understand this important improvement in the error messaging introduced in the Constraint Model.