我目前正在尝试找到一个解决方案,如果测试方法生成的线程中发生异常,如何确保测试失败。
我不想在单元测试中开始讨论多个线程。 => "单元测试".Replace("单元","集成");
我已经在几个论坛上阅读了很多帖子,我知道 CrossThreadTestRunner,但我正在寻找一个集成到 nunit 中的解决方案,并且不需要重写大量测试。
I currently trying to find a solution, how to ensure that a test fails if an exception occurs in a thread which is spawn by the test method.
I DON'T want to start a discussion about more than one thread in a unit test. => "unit test".Replace("unit","integration");
I already read a lot of threads in several forums, I know about CrossThreadTestRunner, but I'm searching for a solution whichs integrates into nunit, and does not require to rewrite a lot of tests.
发布评论
评论(3)
非测试线程(即其他生成的线程)上的异常不会导致测试失败的原因是 NUnit 默认配置为使用 legacyUnhandledExceptionPolicy 这是一个.Net进程级别设置,可以通过app.config应用,即:
启用此设置(即将其设置为“1”)会导致异常不会在主线程上发生的情况将被忽略。
我写了一篇文章,更详细地介绍了 ReSharper 测试运行程序的这个问题,但它同样适用于 NUnit 测试运行程序:
https://web.archive.org/web/20101006004301/http://gojisoft.com/blog/2010/05/14/resharper-test-runner-hidden-thread-exceptions/)
The reason that exceptions on non-test threads (i.e. other spawned threads) do not cause tests to fail is that NUnit is configured by default to use legacyUnhandledExceptionPolicy which is a .Net process level setting which can be applied via app.config, i.e.:
Enabling this setting (i.e. setting it to "1") causes exceptions which do not occur on the main thread to be ignored.
I wrote an article which goes into more detail in reference to this issue with the ReSharper test runner, but it applies equally to the NUnit test runner:
https://web.archive.org/web/20101006004301/http://gojisoft.com/blog/2010/05/14/resharper-test-runner-hidden-thread-exceptions/)
我遇到了同样的问题,我的解决方案是捕获异常并增加异常计数器,因此 Test 方法只需断言异常计数器为 0 即可确认没有线程发生异常。
删除特定环境内容后我的测试代码的摘录:
...
I just had the same problem, my solution is to catch the exception and increment an exception counter, so the Test method just have to assert the exception counter is 0 to confirm no thread got an exception.
An extract of my test code once specific environment stuff is removed:
…
我通过为 nunit 创建一个插件解决了这个问题,它“安装”了一个 ITestDecorator。
I solved the problem by creating an addin for nunit, which "installs" an ITestDecorator.