Before I start, I want to make it clear that I've already checked for solutions in both this question and this question.
The Method to Test
public static DataSet ExecuteDataSet(this SqlConnection connection, string sql)
{
if (null == connection || null == sql)
{
throw new ArgumentNullException();
}
using (var command = connection.CreateCommand())
{
// Code elided for brevity
}
}
The Test Methods
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ExecuteDataSetThrowsForNullConnection()
{
((SqlConnection)null).ExecuteDataSet("SELECT TOP 1 * FROM prep");
}
[Test]
public void ExecuteDataSetThrowsForNullSql()
{
Assert.Throws<ArgumentNullException>(
() => Resource.Connection.ExecuteDataSet(null)
);
}
The Odd Behavior
Neither version of the test method is catching the ArgumentNullException
that is thrown immediately upon entering the ExecuteDataSet
method. Control flow proceeds to the next line (using (var command = connection.CreateCommand())
) and a NullReferenceException
is occurring instead (which, of course, isn't handled by either of my test cases because it should never be thrown).
Originally, the first test method (ExecuteDataSetThrowsForNullConnection
) looked just like the second one (ExecuteDataSetThrowsForNullSql
). When Assert.Throws
failed to catch the exception, I did some research and noted that some folks recommended using ExpectedException
instead. I modified the test code accordingly, but to no avail.
For the record, this is 32-bit .NET 3.5 code, tested under NUnit 2.5.9. I'm using TestDriven.NET for Visual Studio integration, and have the latest versions of NCover and NDepend installed.
TL;DR Question
Why aren't the test methods catching the exception that is thrown, and how do I fix it?
EDIT
This version of the test method works.
[Test]
public void ExecuteDataSetThrowsForNullConnection()
{
try
{
((SqlConnection)null).ExecuteDataSet("SELECT TOP 1 * FROM prep");
}
catch(ArgumentNullException e)
{
Assert.AreEqual(true, true);
}
catch (Exception e)
{
Assert.Fail("Expected ArgumentNullException, but {1} was thrown instead.", e.GetType().Name);
}
}