When writing assertions it is annoying to write a string that basically mirrors what the code your testing says. For example:
Debug.Assert(input != null, "input != null");
Similar statements appear when unit testing with tools like NUnit.
With Linq it is now possible to avoid this by using expression trees. The basic idea is to take a boolean assertion function as an expression tree so that we can call ToString() to get the message for the assert.
void Assert<T>(T obj, Expression<Func<T, bool>> test)
{
System.Diagnostics.Debug.Assert(test.Compile().Invoke(obj), test.ToString());
}
This is then called like:
Assert(input, i => i != null);
Given this idea, we can play with the syntax a bit. Using an extension method:
static class Exts
{
public static void MustSatisfy<T>(this T obj, Expression<Func<T, bool>> test)
{
Debug.Assert(test.Compile().Invoke(obj), test.ToString());
}
}
We then have:
input.MustSatisfy(i => i != null)
Another syntax option would be something like:
Assert.That(foo).Satisfies(
i => i > 0,
i => i < 100);
Where we are now passing an array of assertions (using a params arg in the Satisfies method).