C# 没有预期异常的测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9803839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test with NO expected exception
提问by Yury Pogrebnyak
I want to create NUnit test to ensure that my function does not throw an exception. Is there some specific way to do it, or I should just write
我想创建 NUnit 测试以确保我的函数不会引发异常。有什么具体的方法可以做到,或者我应该写
[Test]
public void noExceptionTest() {
testedFunction();
}
and it will succeed if no exception is thrown?
如果不抛出异常,它会成功吗?
采纳答案by sll
Assert.DoesNotThrow(() => { /* custom code block here*/});
OR just method
或只是方法
Assert.DoesNotThrow(() => CallMymethod());
For more details see NUnit Exception Asserts
有关更多详细信息,请参阅NUnit 异常断言
回答by Anton
Yes, no thrown exceptions -> test pass. If there was try-catch block without re-throw, it'll pass too.
是的,没有抛出异常 -> 测试通过。如果有没有重新抛出的 try-catch 块,它也会通过。
回答by Phil
回答by dasblinkenlight
Not throwing an exception is the normal course of action. Your test will successfully verify that an exception is not thrown.
不抛出异常是正常的操作过程。您的测试将成功验证未引发异常。
回答by daryal
I think there is a problem related to unit test logic. If you are expecting a specific exception under certain inputs, you declare it as an expected exception. If you are just checking whether your function behaves properly and no exceptions are expected during this proper behavior, you just write it and if it throws any exception, your test fails.
我认为存在与单元测试逻辑相关的问题。如果您期望在某些输入下出现特定异常,则将其声明为预期异常。如果您只是检查您的函数是否正常运行,并且在此正常行为期间不会出现异常,您只需编写它,如果它抛出任何异常,您的测试就会失败。
Your code seems to be working properly, on the other hand, only checking no exceptions may not be the proper way for unit testing. In unit tests, generally you expect some outputs (expected values), you have some actual outputs (actual values) and you assert that expected and actual values are the same.
您的代码似乎工作正常,另一方面,只检查没有异常可能不是单元测试的正确方法。在单元测试中,通常您期望一些输出(预期值),您有一些实际输出(实际值)并且您断言预期值和实际值相同。
回答by Hyman Ukleja
Using NUnit 3.0 Constraint Modeltype assertions the code would look as follows:
使用 NUnit 3.0约束模型类型断言,代码如下所示:
Assert.That(() => SomeMethod(actual), Throws.Nothing);
Assert.That(() => SomeMethod(actual), Throws.Nothing);
This example is taken from NUnit wiki.
这个例子取自NUnit wiki。

