斷言是被用來檢查非法情況而不是錯誤情況,即在該程序正常工作時絕不應該發生的非法情況,用來幫助開發人員對問題的快速定位。異常處理用於對程序發生異常情況的處理,增強程序的健壯性、容錯性,減少程序使用中對用戶不有好的行為,不讓(通常也不必)用戶知道發生了什么錯誤。
實際開發中,我們通常將Assert與異常混淆, 不知道什么時候使用Assert,什么時候使用異常處理。或者不用Assert,將一切情況都歸為異常。這樣一來,就掩蓋了問題,當問題發生的時候,很難進行定位,而這些問題本該是在開發的時候就解決掉的。同時,也增加了開銷(在c#中,debug.Assert()編譯成release版本時,不會產生任何代碼,而try/catch在debug/release版本中都是有代碼產生,運行時需要開銷)。
Assert類位於Microsoft.VisualStudio.TestTools.UnitTesting 命名空間下,該命名空間提供支持單元測試的類。此命名空間包含許多屬性,這些屬性為測試引擎標識有關數據源、方法執行順序、程序管理、代理/主機信息以及部署數據的測試信息。Microsoft.VisualStudio.TestTools.UnitTesting 命名空間還包含自定義單元測試異常。
MSDN中,有詳細的Assert類的公共方法:http://msdn.microsoft.com/zh-cn/library/Microsoft.VisualStudio.TestTools.UnitTesting.Assert(v=vs.100).aspx。
本文簡單歸類一些簡單的使用方法。掌握Assert類,一個BestPractice就是,了解Assert的幾個主要方法,然后熟悉其重寫方法即可,整理表格如下:
Name |
Description |
AreEqual(+18) AreNotEqual(+18) |
Verifies that specified values are equal(or not equal). The assertion fails if the values are not equal(or equal). Displays a message if the assertion fails, and applies the specified formatting to it.(if available) |
AreSame(+3) |
Verifies that specified object variables refer to the same object. The assertion fails if they refer to different objects. Displays a message if the assertion fails, and applies the specified formatting to it.(if available) |
Equal |
Determines whether two objects are equal. |
Fail(+3) |
Fails an assertion without checking any conditions. Displays a message, and applies the specified formatting to it.(if available) |
InConclusive(+3) |
Indicates that an assertion cannot be proven true or false. Also used to indicate an assertion that has not yet been implemented. Displays a message, and applies the specified formatting to it.(if available) |
IsFalse(+3) IsTrue(+3) |
Verifies that a specified condition is false(or true). The assertion fails if the condition is true(not true). Displays a message, and applies the specified formatting to it.(if available) |
IsInstanceOfType(+3) IsNotInstanceOfType(+3) |
Verifies that a specified object is(or is not) an instance of the specified type. The assertion fails if the type is not(or is) found in the inheritance hierarchy of the object. Displays a message, and applies the specified formatting to it.(if available) |
IsNull(+3) IsNotNull(+3) |
Verifies that a specified object is null(or not null) . The assertion fails if it is not null(or is null). Displays a message if the assertion fails, and applies the specified formatting to it.(if available) |
ReplaceNullChars |
In a string, replaces null characters ('\0') with "\\0". |
關於異常處理, 在編寫代碼的時候,應充分考慮各種具體異常,而不簡單的catch到Exception,寫出更健壯的代碼。
通常來說,能夠用Assert的地方,都可以用try/catch處理 。但這不是好習慣。We need to "Writing Clean Code".
文中相關擴展連接,
Microsoft.VisualStudio.TestTools.UnitTesting Namespace
A Unit Testing Walkthrough with Visual Studio Team Test
Lionden 2015年1月18日
E-mail:hsdlionden@hotmail.com
轉載請注明原文地址和博客園Lionden:http://www.cnblogs.com/lionden/