Sunday, May 17, 2009

Cast null values in tests

My first tests of classes are often tests that asserts that the constructor throws ArgumentNullException for null arguments, something like this:

public void constructor_throws_when_fileSystem_is_null()
    Assert.Throws<ArgumentNullException>(() =>
            new TransactionalFileSystem((IFileSystem)null, this.transactionManager);

As you see I explicitly cast the null value to the type of the parameter in the constructor signature, this is benefitial for two reasons:

  1. It reads better, the reader know what it is that is NOT passed in.
  2. Several times in the past I have refactored and reordered the parameters in the constructor with the result that the tests test the wrong parameters this is avoided this way.


  1. The MbUnit Assert.Throws is indeed a great way to verify that an exception was thrown at the expected line. But when the test method has only 1 line of code as in your example (invoking the constructor of the tested type), maybe it is easier to just decorate the test method with [ExpectedArgumentNullException].

  2. Yann, that's totally beside the point of the post, also it's not MBUnit, it's NUnit. The syntax was not even introduced by MBUnit, it was introduced by xUnit. I prefer it this way, mainly because I have a snippet for it but I guess that's a matter of taste. Still, it has absolutely nothing to do with what the post is about.