我已經通過實現NUnit.Framework.IExpectException
接口創建了一個預期的異常屬性,如文檔(http://www.nunit.org/index.php?p=exception&r=2.6.2)所示,它工作得很好。它驗證拋出的異常屬於正確的類型,並驗證異常中某些屬性的值。單元測試IExpectException的實現
[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);
}
}
我的問題是,我想單元測試的屬性,但我不明白的方式來測試以下情況:
A unit test that have the attribute should fail if no exception are thrown.
我只是想不出辦法爲這種情況編寫一個單元測試,因爲在拋出異常時不會調用HandleException。
有什麼建議嗎?