【问题标题】:Explicitly setting a test to pass/fail?明确设置测试通过/失败?
【发布时间】:2012-01-12 11:40:06
【问题描述】:

在下面的测试中,如果进入catch块我想说明测试通过了。如果绕过了 catch 块,我希望测试失败。

有没有办法做到这一点,还是我错过了应该如何构建测试的要点?

[TestMethod]
public void CommandExecutionWillThrowExceptionIfUserDoesNotHaveEnoughEminence()
{
    IUserCommand cmd = CreateDummyCommand("TEST", 10, 10);
    IUser user = new User("chris", 40);

    try
    {
        cmd.Execute(user);
    }
    catch(UserCannotExecuteCommandException e)
    {
        //Test Passed
    }

    // Test Failed
}

【问题讨论】:

标签: c# unit-testing testing


【解决方案1】:

当我遇到类似情况时,我倾向于使用这种模式:

// ...
catch (UserCannotExecuteCommandException e)
{
    return;    // Test Passed
}

Assert.Fail();    // Test Failed -- expected exception not thrown

【讨论】:

    【解决方案2】:

    声明测试抛出 UserCannotExecuteCommandException,当发生这种情况时测试将成功

    [ExpectedException( typeof( UserCannotExecuteCommandException) )]
    

    【讨论】:

    • 但是如果抛出异常,测试是否也成功?如果没有抛出异常,OP 需要测试失败。
    • 谢谢。当抛出实际异常时,如何防止 Visual Studio 停止执行测试?例如,我必须在测试继续之前按 F5/Continue 并且可以标记为通过。
    • @Chris:运行测试没有调试(CTRL R,T)
    【解决方案3】:

    我建议使用Assert.Throws() 方法:

    Assert.Throws<UserCannotExecuteCommandException>() => cmd.Execute(user));
    

    Id 可以满足您的所有需求。它期望在执行cmd.Execute() 方法时会抛出UserCannotExecuteCommandException 类型的异常,否则会自动将测试标记为失败。

    【讨论】:

      【解决方案4】:

      由于[ExpectedException(...)] 被认为是一种不好的做法,您可能会使用:

      • MSTest:Assert.ThrowsException&lt;UserCannotExecuteCommandException &gt;( () =&gt; cmd.Execute(user) );
      • N 单元:Assert.Throws&lt;UserCannotExecuteCommandException &gt;( () =&gt; cmd.Execute(user) );

      然后你就可以指出哪一行应该引发异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-14
        • 2019-07-31
        • 1970-01-01
        • 2015-07-08
        • 2020-05-11
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        相关资源
        最近更新 更多