预期异常断言

2023-12-25

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

Usage:

var exception = AssertCatch<ArgumentOutOfRangeException>(() => /* EXECUTE */);
Assert.AreEqual("foo", exception.Message);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

预期异常断言 的相关文章

随机推荐