【发布时间】:2013-12-10 12:07:27
【问题描述】:
我需要为下一个函数写一个单元测试,我看到我可以使用 [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,因为如果测试方法代码的任何部分发生异常,此属性会使测试通过。Assert.Throws允许测试发生异常的代码的确切位置。 -
@sthotakura MSTest 没有 Assert.Throws 除非您编写自定义的,无论如何这是首选的 MSTest 异常处理。类似于 NUnit :) 我的答案中有一个链接
-
@Spock 我不知道,谢谢!
-
@sthotakura, Spock 我在我的回答中也为
Throws提供了一个示例实现:stackoverflow.com/a/45270837/67824。
标签: c# unit-testing testing expected-exception