断言是被用来检查非法状况而不是错误状况,即在该程序正常工做时毫不应该发生的非法状况,用来帮助开发人员对问题的快速定位。异常处理用于对程序发生异常状况的处理,加强程序的健壮性、容错性,减小程序使用中对用户不有好的行为,不让(一般也没必要)用户知道发生了什么错误。程序员
实际开发中,咱们一般将Assert与异常混淆, 不知道何时使用Assert,何时使用异常处理。或者不用Assert,将一切状况都归为异常。这样一来,就掩盖了问题,当问题发生的时候,很难进行定位,而这些问题本该是在开发的时候就解决掉的。同时,也增长了开销(在c#中,debug.Assert()编译成release版本时,不会产生任何代码,而try/catch在debug/release版本中都是有代码产生,运行时须要开销)。算法
Assert类位于Microsoft.VisualStudio.TestTools.UnitTesting 命名空间下,该命名空间提供支持单元测试的类。此命名空间包含许多属性,这些属性为测试引擎标识有关数据源、方法执行顺序、程序管理、代理/主机信息以及部署数据的测试信息。Microsoft.VisualStudio.TestTools.UnitTesting 命名空间还包含自定义单元测试异常。c#
MSDN中,有详细的Assert类的公共方法:http://msdn.microsoft.com/zh-cn/library/Microsoft.VisualStudio.TestTools.UnitTesting.Assert(v=vs.100).aspx。app
本文简单归类一些简单的使用方法。掌握Assert类,一个BestPractice就是,了解Assert的几个主要方法,而后熟悉其重写方法便可,整理表格以下:dom
Name单元测试 |
Description测试 |
AreEqual(+18)spa AreNotEqual(+18)debug |
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".
文中相关扩展链接,