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

RowTests with NUnit 2.4

Standard

I had some time last week and therefore I played around with the new extensibility features of NUnit 2.4. I wanted to know, how difficult it is to implement the RowTest feature of MbUnit as NUnit Addin. Two hours later the RowTest Extension for NUnit was ready. I released the extension under the MIT license. The following code snippet shows you how to use the extension:

    [TestFixture]
    public class RowTestSample
    {
         [RowTest]
         [Row( 1000, 10, 100.0000)]
         [Row(-1000, 10, -100.0000)]
         [Row( 1000, 7, 142.85715)]
         [Row( 1000, 0.00001, 100000000)]
         [Row(4195835, 3145729, 1.3338196)]
         public void DivisionTest(double num, double den, double res)
         {
            Assert.AreEqual(res, num / den, 0.00001);
         }
    }

The current release does not support all features of MbUnit RowTests, e.g. Exceptions cannot be tested.