Wednesday 20 August 2014

a gotcha with nunit

Was writing a unit test with nunit the other day which went something like :



[Test]
[ExpectedException(typeof(JobExecutionException))]
public void Failure_To_Get_Companies_Sends_Message_And_Logs()
{
   var mockBillingService = new Mock<IBillingService>();
   var mockCompanyService = new Mock<ICompanyService>();
   var mockLogger = new Mock<ILog>();
   var mockJobExectionContext = new Mock<IJobExecutionContext>();

   mockCompanyService.Setup(m => m.CompaniesToBeBilled).Throws(new Exception("problem getting the customers"));
           
   var job = new CustomerBillingJob(mockCompanyService.Object, mockBillingService.Object, mockLogger.Object);
           
    job.Execute(mockJobExectionContext.Object);
    mockLogger.Verify(m => m.Fatal("whoops", It.IsAny<Exception>()), Times.AtLeastOnce());
}

A subtle thing to be wary of is the verify call at the end, we seem to get funny behaviour when we use expected exception in our test and the call to verify seems to get ignored, i'm assuming that all nunit cares about is the fact that the test did throw the expected exception.

I have started rearranging the test so the call to execute is wrapped with a try catch and only handles the exception type you are expecting and does an assertion on that exception being generated.  It is also too easy to put at the top that you expect an exception of type exception too meaning you are not really testing the actual exception type you want to test.

hope that helps.