ExpectedException断言

Rub*_*nex 9 c# testing unit-testing expected-exception

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

这里将使用代码来测试应该抛出的异常

    [TestMethod] 
    [ExpectedException(ArgumentOutOfRangeException(ArgumentException), "message")]
    public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
    {
        // PREPARE
        // EXECUTE
        // ASSERT
    }
Run Code Online (Sandbox Code Playgroud)

我也不知道要为例外做出断言.

Ser*_*kiy 24

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

[TestMethod] 
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void FailIfEnumIsNotDefined_Check_That_The_Value_Is_Not_Enum()
{
    // PREPARE
    // EXECUTE
    // NO ASSERT!!
}
Run Code Online (Sandbox Code Playgroud)

如果要声明其他异常参数,则应try..catch在测试方法中使用:

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

    try
    {
       // EXECUTE
       Assert.Fail()
    }
    catch(Exception exception)
    {        
        // ASSERT EXCEPTION DETAILS
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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");
}
Run Code Online (Sandbox Code Playgroud)

用法:

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