Wednesday, April 18, 2007

Unit Testing Expected Exception

I have seen and implemented a few different patterns to unit test expected exceptions. This was one that I saw the other day that seems to be the pinnacle pattern to unit test an expected exception.

The key aspects of it are:
• Declaration of a variable scoped to the entire method to hold a reference to an exception (Dim theExpectedException As ArgumentNullException)
• Catching the exception @ the most granular level that it HAS to be the expected exception, by using the correct exception type (ex As ArgumentNullException) and the when clause (When ex.ParamName = "lab").
• Asserting on the condition that the exception IsNotNull proves it was thrown and caught in the method.


Sub NewILabAdornmentsNegativeILabNull()

Dim lab As ILab = Nothing
Dim adornments As IDisplayLine.LabAdornmentStrings = None
Dim target As IDisplayLine
Dim theExpectedException As ArgumentNullException = Nothing

Try
target = Factory.DisplayLine(lab, adornments)
Catch ex As ArgumentNullException When ex.ParamName = "lab"
theExpectedException = ex
End Try

Assert.IsNotNull(theExpectedException, "Proves Factory.DisplayLine(ILab,LabAdornmentStrings) throws an ArgumentNullException exception when passed a null lab.")
End Sub

No comments: