我需要編寫用於下一功能的單元測試和我看到我可以使用[的ExpectedException]的ExpectedException斷言
這是要測試的功能。
public static T FailIfEnumIsNotDefined<T>(this T enumValue, string message = null)
where T:struct
{
var enumType = typeof (T);
if (!enumType.IsEnum)
{
throw new ArgumentOutOfRangeException(string.Format("Type {0} is not an Enum, therefore it cannot be checked if it is Defined not have defined.", enumType.FullName));
}
else if (!Enum.IsDefined(enumType, enumValue))
{
throw new ArgumentOutOfRangeException(string.Format("{1} Value {0} is not does not have defined value in Enum of type {0}. It should not be...", enumType.FullName, message ?? ""));
}
return enumValue;
}
這裏會去的代碼來測試應該在異常被拋出
[TestMethod]
[ExpectedException(ArgumentOutOfRangeException(ArgumentException), "message")]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
// EXECUTE
// ASSERT
}
我沒有想法不得不作出的例外斷言無論是。
使用'Assert.Throws()'而不是'ExpectedException',因爲該屬性使得測試通過,如果exc eption發生在測試方法代碼的任何部分。 'Assert.Throws'允許在出現異常的地方測試代碼的確切位置。 – sthotakura
@sthotakura MSTest不具有Assert.Throws,除非您編寫自定義的一個,無論如何,這是首選的MSTest異常處理。類似於NUnit :)我的回答中有一個鏈接 – Spock
@Spock我不知道,謝謝! – sthotakura