gpt4 book ai didi

c# - 预期异常断言

转载 作者:太空狗 更新时间:2023-10-29 18:03:21 25 4
gpt4 key购买 nike

我需要为下一个函数编写单元测试,我看到我可以使用 [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
}

我也不知道必须对异常进行断言。

最佳答案

ExpectedException 只是断言指定类型的异常将被测试方法抛出:

[TestMethod] 
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE
// EXECUTE
// NO ASSERT!!
}

如果你想断言异常的其他参数,那么你应该在你的测试方法中使用try..catch:

[TestMethod]     
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
// PREPARE

try
{
// EXECUTE
Assert.Fail()
}
catch(Exception exception)
{
// ASSERT EXCEPTION DETAILS
}
}

您可以编写自己的方法来断言抛出异常以避免一遍又一遍地重复相同的测试代码:

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");
}

用法:

var exception = AssertCatch<ArgumentOutOfRangeException>(() => /* EXECUTE */);
Assert.AreEqual("foo", exception.Message);

关于c# - 预期异常断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com