Verifying exceptions using IExpectException

The unit tests for NUnit contain an interesting pattern for verifying exception details. The abstract class MessageChecker in assembly nunit.framework.tests implements IExpectException, an interface introduced with NUnit 2.4. Test cases in derived test fixtures set the protected field expectedMessage to the expected exception message which can span several lines or include data from the test setup.

Here is another example:

public class FileNotFoundExceptionChecker : IExpectException
{
  private string _expectedFileName;

  public FileNotFoundExceptionChecker()
  {
  }

  public void HandleException(Exception ex)
  {
    if (_expectedFileName == null)
      return;

    Assert.IsInstanceOfType (typeof (FileNotFoundException), ex);
    FileNotFoundException fileNotFoundException = (FileNotFoundException) ex;

    StringAssert.Contains(_expectedFileName, fileNotFoundException.Message);
    Assert.AreEqual(_expectedFileName, fileNotFoundException.FileName);
  }

  protected void ExpectMissingFile(string fileName)
  {
    _expectedFileName = fileName;
  }
}

[TestFixture]
public class FileTest : FileNotFoundExceptionChecker
{
  [Test]
  [ExpectedException(typeof(FileNotFoundException))]
  public void ReadAllBytes()
  {
    string fileName = @"C:notexistingfile.txt";
    ExpectMissingFile(fileName);

    File.ReadAllBytes(fileName);
  }
}

Technorati Tags ,

This entry was posted in .NET Development, TDD and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*