This blog has been moved to http://info.timkellogg.me/blog/

Saturday, February 26, 2011

NUnit Extension Methods

I've always used NUnit for testing code so it's naturally the framework I'm most familiar with (I haven't used anything else). I learned unit testing using the classic Assert.AreEqual(expected, actual) methods. Although, I was finding my tests slightly confusing to read - I sometimes can't remember which comes first, expected or actual.

More recently I've been getting into v2.5 including the new asserts - Assert.That(actual, Is.EqualTo(expected)). I think this makes a lot of sense and I often find myself using Assert.That most of the time just because it makes sense.

Recently, a coworker created a few extension methods that I'm finding quite handy:

public static void ShouldBe(this object @this, object expected) {
    Assert.AreEqual((dynamic)expected, (dynamic)@this);
}
public static void ShouldNotBe(this object @this, object expected) {
    Assert.AreNotEqual((dynamic)expected, (dynamic)@this);
}
public static void ShouldBeNull(this object @this) {
    Assert.IsNull(@this);
}
public static void ShouldNotBeNull(this object @this) {
    Assert.IsNotNull(@this);
}

I've completely fallen in love with how this reads: actual.ShouldBe(expected). It also makes me giggle to do actual.ShouldBeNull() (Don't you love extension methods?). This makes unit testing so easy...

No comments:

Post a Comment