Unit Testing: Using Extension Methods for better Exception Catching

Improving unit testing, and use some sleek OOP too.

Let’s say that we want to test a call to a basic stored procedure, where @ClientID is required.

EXEC MYDB.MYSCHEMA.GetClients @ClientID = 10001

Now we want to test the database call in a unit test.  If we don’t pass in @ClientID, we should expect a SqlException, right?  So let’s test that.

// assign
int? testClientID = null;
bool missingClientIDErrorOccurred = false;

// act
try
{
MyDataAccess.GetClients(testClientID); 
}
catch (SqlException)
{
missingClientIDErrorOccurred = true;
}

// assert
Assert.IsTrue(missingClientIDErrorOccurred);

All looks good, right?  We expect a SqlException that says something like “Procedure X expects parameter Y, which was not supplied” (or something close to it).

But what happens if any other SqlException occurs?  Our test will pass.  Oops.  Can we narrow down our catch statement?  Absolutely.  We can find out if the SqlException caught is, in fact, caused by our missing @ClientID parameter by just checking the Message property of the exception.

catch (SqlException e)
{
	missingClientIDErrorOccurred = e.Message
	   .Contains("expects parameter '@ClientID', which was not supplied.");
}

Gravy. Now our test is just that much more accurate, and we shouldn’t have to worry later about incorrect test results. But wait… as OO programmers we like to be efficient, and hard-coding message strings is an obvious code-smell. Let’s improve it using extension methods.

public static bool CausedByMissingParameter(this SqlException exception, string missingParameterName)
{
	string missingParameterErrorMessage = 
	   string.Format(
	   	   "expects parameter '{0}', which was not supplied.", 
	   	   missingParameterName);
       return exception.Message.Contains(missingParameterErrorMessage);
}

Perfect, now we’re good to go. And of course we can reuse this extension method every time we want to write a similar test. Efficiency win. Now, the finish code looks pretty sleek and simple.

//act
try
{
	MyDataAccess.GetClients(testClientID); 
}
	catch (SqlException e)
{
	missingClientIDErrorOccurred = e.CausedByMissingParameter("@CommentID");
}

Your Thoughts?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s