如何期待异常并仍然通过测试?

O.O*_*O.O 0 c# unit-testing nmock .net-2.0

我有这个:

  Expect.Once.On( someObj ).Method( "SomeMethod" )
    .With(1) // correct value is 2, I want this to fail
    .Will( Throw.Exception( new Exception() ) );
Run Code Online (Sandbox Code Playgroud)

当nmock检测到我输入1而不是2时,会抛出异常.但是,测试失败(红色)而不是传递.即使我期待例外,如何使这个测试通过?

Lee*_*Lee 5

如果您正在使用NUnit,那么您可以:

Assert.Throws<Exception>(() => { someObj.SomeMethod(1); });
Run Code Online (Sandbox Code Playgroud)

您还可以使用ExpectedException属性修饰测试,但如果Exception抛出任何测试,则会导致测试通过,而不仅仅是您要测试的语句.

编辑:如果您正在使用MSTest,据我所知,您只能使用属性来预期异常,即

[ExpectedException(typeof(Exception)]
public void TestMethod() { ... }
Run Code Online (Sandbox Code Playgroud)

您应该考虑从模拟中抛出一个更具体的异常类型,并期望该类型而不是普通类型Exception.

您还可以定义自己的方法来复制NUnit功能:

public static class ExceptionAssert
{
    public static void Throws<T>(Action act) where T : Exception
    {
        try
        {
            act();
        }
        catch (T ex)
        {
            return;
        }
        catch (Exception ex)
        {
            Assert.Fail(string.Format("Unexpected exception of type {0} thrown", ex.GetType().Name));
        }

        Assert.Fail(string.Format("Expected exception of type {0}", typeof(T).Name));
    }
}
Run Code Online (Sandbox Code Playgroud)