问题描述
我需要编写单元测试下一个功能,我看到我可以使用[的ExpectedException]
I need to write a unit test for the next function and I saw I can use [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;
}
在这里会去的代码来测试,都应该被扔例外
and here would go the code to test the exceptions that are supposed to be threw
[TestMethod]
[ExpectedException(ArgumentOutOfRangeException(ArgumentException), "message")]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
// EXECUTE
// ASSERT
}
我没有想法已经作出的例外或者断言。
I don't have idea have to make the assert for the exceptions either.
推荐答案
的ExpectedException
只是断言指定类型的异常将被试验方法抛出:
ExpectedException
just asserts that exception of specified type will be thrown by test method:
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
// EXECUTE
// NO ASSERT!!
}
如果您想断言异常的其他参数,那么你应该使用在try..catch
在您的测试方法:
If you want to assert other parameters of exception, then you should use try..catch
in your test method:
[TestMethod]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
try
{
// EXECUTE
Assert.Fail()
}
catch(Exception exception)
{
// ASSERT EXCEPTION DETAILS
}
}
您可以编写自己的断言异常的方法被抛出,以避免一遍又一遍的重复相同的测试代码:
You can write your own method for asserting exception was thrown to avoid repeating same test code over and over again:
public TException AssertCatch<TException>(Action action)
where TException : Exception
{
try
{
action();
}
catch (TException exception)
{
return exception;
}
throw new AssertFailedException("Expected exception of type " +
typeof(TException) + " was not thrown");
}
用法:
Usage:
var exception = AssertCatch<ArgumentOutOfRangeException>(() => /* EXECUTE */);
Assert.AreEqual("foo", exception.Message);
这篇关于的ExpectedException断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!