Verifying Exceptions using IExpectException

Standard

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);
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *