[C#.NET] 單元測試的異常測試
除了正常的方法應該被測試到之外,程式裡的每一條分支也應該被測試到,這當然包含異常(Exception),比如說我寫了一個方法
/// <summary>
/// 字串加密
/// </summary>
/// <param name="SourceString">原始字串</param>
/// <returns>返回 Base64 格式字串</returns>
public string EncryptStringToBase64String(string SourceString)
{
if (string.IsNullOrEmpty(SourceString))
throw new NotSupportedException("SourceString");
byte[] dataByteArray = this.EncryptStringToBytes(SourceString);
string encryptString = Convert.ToBase64String(dataByteArray);
return encryptString;
}
這裡有兩條分支,一條是正常的分支一條是例外的分支,正常的分支我們
正常的分支我這樣寫:
public void EncryptStringToBase64StringTest()
{
AbsEncryptCryptoServiceBase target = CreateAbsDesEncryptCryptoServiceBase();
string SourceString =
@"http://webhd.xuite.net/_oops/fgriasa/cn8
http://webhd.xuite.net/_oops/fgriasa/u4g
http://webhd.xuite.net/_oops/fgriasa/t64
http://webhd.xuite.net/_oops/fgriasa/o76
http://webhd.xuite.net/_oops/fgriasa/2c6
http://webhd.xuite.net/_oops/fgriasa/cqg
http://webhd.xuite.net/_oops/fgriasa/1dt
http://webhd.xuite.net/_oops/fgriasa/xaz
http://webhd.xuite.net/_oops/fgriasa/tkh
http://webhd.xuite.net/_oops/fgriasa/iqf
http://webhd.xuite.net/_oops/fgriasa/sye
http://webhd.xuite.net/_oops/fgriasa/8s4
http://webhd.xuite.net/_oops/fgriasa/zgi
解壓密碼
aiml.fgriasa.by.P2P101.FDZONE.ORG
在主場背水一戰的曼菲斯灰熊隊,面對快艇的第五戰,在第一節就以36-22取得大幅領先,不過快艇步步為營,在第三節最多曾經落後24分之後,逐步收復失土,第四節頗有重演第一戰大逆轉的味道。不過保羅(Chris Paul)此時手傷退場,快艇無力反擊,終場就以80-92敗下陣來,灰熊成功扳回一城,將系列賽延長到在洛杉磯的第六戰。
「我們已經陷入背水一戰的處境。」灰熊中鋒蓋索(Marc Gasol)表示:「我們現在還是如此,我們還沒有完成任何事情,而我們希望能夠打回洛杉磯,然後再打出一場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jvOLf9VwEZ55wI4tA8McIwoUBKuw1oRjQPuUnmuZJ1HMfWkmL93cGEOJeUYuhV3CNKpsvZvKitbh9eStmDvE4Q+jBJHrRfC5Fol6F9nYGfO9hkssRTpwF+h4dTKLEsV9JWRS0hnW11XLQZP/5p3vpNozlepBmiKbjGgyRLFFcbV60BELhq56IY5u33M8TDyic8/lYOHH+DBl5CkW++ZTfFJnp7R/kzO0ai0gJUtPqX1nihfuJvaPGtgInbOr27oGsj48nfRBlqyxkKMwwYxfxkvZek0TRYsNsBX9gJpp9koaeKg3qqcD7ex7mpk1q5QUwVHMoZlE7pc3kelBQeUfoVUt7X5MUrK/prncGSFejw42XFUPNYstMJ/ZYNJPA6DGNcwBT2bdTqbovgjiYf3P5/FfpC9q7HA1+UN5cDRjoxv75tzRU4NyOdd5JR4L7eN33v1G9+T+ZYcmiwkWI+/Je1I3HBDBqbaXIwR9eFgmNaXNBmjkJuvoh5ouqBrNPLtJfs4LXmaGeZCmEz9ZosHkT8PG/zybCphsoHENHHvDtgiVNBofwGioKsWxOUM3YzChkW+zO3ZgP8FTX1aSjVpq1/SN2wrGxAheP4NqHv4YJPHMvq+eslsok3m3";
var encrypt = target.EncryptStringToBase64String(SourceString);
var base64Bytes = Convert.FromBase64String(encrypt);
var salt = saltDecode(base64Bytes);
var actual = Convert.ToBase64String(salt.ToArray());
Assert.AreEqual(expected, actual);
}
觀察一下涵蓋率,有一條例外的分支沒測到
別忘了,例外的分支也要測試,以確保結果如我們所期望,我們在測試方法裡定義 ExpectedException 類別,用它來補捉我們所期待的例外。
[ExpectedException(typeof(NotSupportedException))]
public void InvaildEncryptStringToBase64StringTest()
{
AbsEncryptCryptoServiceBase target = CreateAbsDesEncryptCryptoServiceBase();
string SourceString = "";
var encrypt = target.EncryptStringToBase64String(SourceString);
}
執行結果
測試涵蓋也覆蓋到 throw
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET