
.NET 1.1+NUnit Expected Exceptions
When code enters an unexpected state, or when a member is called with invalid parameters, it is usual to throw an exception. When writing unit tests, the test code should ensure that the correct exceptions are thrown.
Testing For Exceptions
In a previous article, as part of the Automated Unit Testing tutorial, I explained the use of the NUnit Exception assertions. These allow you to test that specific code, provided using a delegate or lambda expression, throws an specific exception or an exception of a derived type. You can also test that a code fragment executes without raising an exception.
Another way to check for an exception being thrown is to use NUnit's ExpectedException attribute. This attribute is applied to a test method in addition to the Test attribute. The simplest form of the attribute requires a single parameter containing the type of the exception that is expected. If no exception is thrown, or if the type of the exception is of a different type, the test fails.
The following code shows three tests. The first passes as the correct exception is thrown. The second fails as it does not generate an exception. The third fails because the exception is of the incorrect type, even though ArgumentNullException is a subtype of the expected ArgumentException.
[Test, ExpectedException(typeof(ArgumentException))]
public void PassingTest()
{
throw new ArgumentException();
}
[Test, ExpectedException(typeof(ArgumentException))]
public void FailingTestNoException()
{
// No throw
}
[Test, ExpectedException(typeof(ArgumentException))]
public void FailingTestWrongType()
{
throw new ArgumentNullException();
}
Providing the Exception Type as a String
In the current version of NUnit, you can elect to provide the fully qualified name of the expected exception as a string. This means that you do not have to add a reference to the assembly that declares the exception. However, you must ensure that you enter the name accurately as misspelling the exception name will give invalid test results.
The following test checks for a SoapException being thrown without the need to reference the System.Web.Services DLL.
[Test, ExpectedException("System.Web.Services.Protocols.SoapException")]
public void TestByName()
{
}
8 June 2011