I've created an expected exception attribute by implementing the NUnit.Framework.IExpectException
interface, as documented there (http://www.nunit.org/index.php?p=exception&r=2.6.2 ) and it works pretty well. It validates that the thrown exception is of the right type and validates the value of some properties on the exception.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class ExpectedHttpErrorExceptionAttribute : ExpectedExceptionAttribute, IExpectException
{
public HttpStatusCode StatusCode { get; set; }
public ExpectedHttpErrorExceptionAttribute()
:base(typeof(HttpError))
{}
public ExpectedHttpErrorExceptionAttribute(HttpStatusCode statusCode)
:this()
{
StatusCode = statusCode;
}
public void HandleException(Exception ex)
{
Assert.That(ex, Is.TypeOf(ExpectedException), "Expected exception of type '{0}' but an exception of type '{1}' has been throwned.", typeof(HttpError).FullName, ex.GetType().FullName);
var httpStatusCode = ((HttpError) ex).StatusCode;
Assert.That(httpStatusCode, Is.EqualTo(StatusCode), "Expected status code '{0}' but was '{1}'.", StatusCode, httpStatusCode);
}
}
My problem is that I want to unit test that attribute, but I can't figure a way to test the following case :
A unit test that have the attribute should fail if no exception are thrown.
I just can't figure a way to write a unit test for that case, since the HandleException is not called when no exception are thrown.
Any suggestion?