Monday, January 19, 2009

Assert++

My latest extension method allows you to specify your asserts in a more natural way. It also tells you the set of asserts that fail (a nod towards Fit).

Usage:

model.Check(c=>c.User == "Mr Dee"
&& Revision == 5
&& IsRelevant);


And here's the more readable assertion method:

NUnit.Framework.AssertionException: These constraints do not hold:

c => (c.User = "Mr Dee")

c => (c.Revision = 5)

c => c.IsRelevant

For 'SvnTracker.Model.LogEntry'


(Java guys don't get jealous - check out HamCrest). All that is left is to dig a little in the expression tree and say what value c.Revision was. Tomorrow!

Here's the code:
(error handling will come later)

public static void Check<T>(this T subject, params Expression<Func<T,bool>> [] funcs)
{
var sb = new StringBuilder();
foreach (var func in funcs)
{
if (!func.Compile()(subject))
{
sb.AppendLine("\r\n" + func);
}
}
string msg = sb.ToString();
if (!String.IsNullOrEmpty(msg))
{
Assert.Fail("These constraints do not hold:\r\n" + msg + "\r\nFor '" + subject + "'");
}
}

No comments: