在 NUnit 中,如何显式地使测试失败
例如下面的代码,
[Test()]
public void Test( )
{
try{
GetNumber( );
}
catch( Exception ex ){
/* fail here */
}
...
}
当 GetNumber 方法抛出异常时,我希望测试失败。
请指教。
非常感谢。
For example the code below,
[Test()]
public void Test( )
{
try{
GetNumber( );
}
catch( Exception ex ){
/* fail here */
}
...
}
I want to fail my test when GetNumber method throw an exception.
Please advise.
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不需要将 GetNumber() 包装在 try/catch 中。如果 GetNumber() 抛出异常,您的测试将失败。
如果您需要显式失败,请使用 Assert.Fail();
You don't need to wrap GetNumber() inside a try/catch. If GetNumber() throws, your test will fail.
If you need to fail it explicitly, use Assert.Fail();
如果
GetNumber()
返回一个值,则您不应该执行您想要执行的操作。相反,您应该断言返回值。如果您不希望出现异常,则不必费心检查异常。 NUnit 框架会处理这个问题并帮助您让测试失败。如果
GetNumber()
不返回值,您可以执行以下三种操作之一:在这种情况下,第一的选项是最明确的。如果您可以验证的唯一有趣的副作用是抛出异常,那么这种情况很常见。但如果
GetNumber()
不返回值,您确实应该考虑重命名您的方法:)If
GetNumber()
returns a value, you shouldn't do what you're trying to do. Instead, you should assert the return value. Don't bother checking for exceptions if you don't expect one to arise. The NUnit framework will take care of that and fail your test for you.If
GetNumber()
doesn't return a value, you can do one of three things:In this case, the first option is the most explicit. This is common if the only interesting side-effect you can validate is if an exception gets thrown. But if
GetNumber()
doesn't return a value, you should really consider renaming your method :)所有测试都应该通过,如果您期望出现异常,则应该使用 ExpectedException 属性。如果您的代码抛出预期的异常,测试就会通过。
All test should pass, if you are expecting an exception you should use ExpectedException attribute. If your code throws the expected exception test will pass.
Assert.Fail()
: http: //www.nunit.org/index.php?p=utilityAsserts&r=2.2.7虽然,可能有一个 Assert.NoThrow 断言,或者类似的东西,这确保了你的方法不会抛出。
Assert.Fail()
: http://www.nunit.org/index.php?p=utilityAsserts&r=2.2.7Although, there is probably an assertion to Assert.NoThrow, or something like that, that ensures your method doesn't throw.
测试失败相当于抛出异常。因此,如果您的方法抛出异常,则测试将失败。
Failing a test is equivalent to throwing an exception from it. Therefore, iff your method throws the test will fail.