Thursday, February 09, 2012

Asserting Exception messages in unit tests

I found a handy little class for checking against specific exception types and their messages which is a nice upgrade from the standard "ExpectedException" attribute.

I must credit the author of this, found on Stack Overflow. Link here: http://stackoverflow.com/questions/113395/how-can-i-test-for-an-expected-exception-with-a-specific-exception-message-from

The class is as follows:


public static class ExceptionAssert
{
  public static T Throws(Action action) where T : Exception
  {
    try
    {
      action();
    }
    catch (T ex)
    {
      return ex;
    }
    Assert.Fail("Exception of type {0} should be thrown.", typeof(T));

    //  The compiler doesn't know that Assert.Fail
    //  will always throw an exception
    return null;
  }
}
An example of a test that makes use of this class is below
[TestMethod]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
{
  OrganizationList organizations = new Organizations();
  organizations.Add(new Organization());
  organizations.Add(new Organization());

  var ex = ExceptionAssert.Throws(
              () => organizations.GetOrganization());
  Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message);
}

No comments:

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Z