項目中我們繼承.net系統異常類做成了一個自定義的異常類:WPSYSException
在實際程式中發現異常情況時,需要構造并抛出此類異常時,代碼如下:
//如果輸入數組為空,報異常
if ((inDoubleArray == null) || (inDoubleArray.Length == 0))
{
//抛出異常
throw new WPSYSException(
null,
ProgID,
strErrPos,
"輸入數組為空",
"申請的錯誤号常量"
);
}
使用Vs2005作單元測試時,測試代碼應寫為以下方式,方可測試程式抛出的異常是否正确:
/// <summary>
///ToOneArray (double[]) 的測試(輸入數組為空)
///</summary>
[TestMethod()]
[ExpectedException(typeof(WPSYSException), "輸入數組為空")]
public void ToOneArrayTest_e1()
{
double[] inDoubleArray = null;
double[] expected = null;
double[] actual;
actual = WP.SEV001.COM.SYS.S000C11006.ToOneArray(inDoubleArray);
}
即,注意在測試方法頭加上次屬性
[ExpectedException(typeof(WPSYSException), "輸入數組為空")]
WPSYSException:自定義異常類
輸入數組為空:異常中的資訊
ExpectedExceptionAttribute (Type, String)
用預期的異常類型以及描述此異常的消息來初始化 ExpectedExceptionAttribute 類的新執行個體。
因WPSYSException為自定義的異常類,所在在測試工程中需要引用包含次異常類的dll或者加入代碼
此前用以下方式也可實作指定錯誤資訊的正确性測試,但不如上述方法規範:
string strErrorInfo = "輸入數組為空";
try
actual = DoubleArrayToOne.ToOne.ToOneArray(inDoubleArray);
catch (System.Exception ex)
Assert.AreEqual(ex.Message, strErrorInfo);