我目前正在尝试找到一个解决方案,如果测试方法产生的线程中发生异常,如何确保测试失败。
我不想在单元测试中开始讨论多个线程。=> "单元测试".Replace("unit","integration");
我已经在几个论坛中阅读了很多帖子,我知道CrossThreadTestRunner,但我正在寻找一个集成到 nunit 中的解决方案,并且不需要重写很多测试。
我目前正在尝试找到一个解决方案,如果测试方法产生的线程中发生异常,如何确保测试失败。
我不想在单元测试中开始讨论多个线程。=> "单元测试".Replace("unit","integration");
我已经在几个论坛中阅读了很多帖子,我知道CrossThreadTestRunner,但我正在寻找一个集成到 nunit 中的解决方案,并且不需要重写很多测试。
非测试线程(即其他衍生线程)上的异常不会导致测试失败的原因是 NUnit 默认配置为使用legacyUnhandledExceptionPolicy,这是一个可以通过 app.config 应用的 .Net 进程级别设置,即:
<legacyUnhandledExceptionPolicy enabled="1"/>
启用此设置(即设置为“1”)会导致主线程上未发生的异常被忽略。
我写了一篇文章,详细介绍了 ReSharper 测试运行器的这个问题,但它同样适用于 NUnit 测试运行器:
http://gojisoft.com/blog/2010/05/14/resharper-test-runner-hidden-thread-exceptions/
我刚刚遇到了同样的问题,我的解决方案是捕获异常并增加一个异常计数器,因此 Test 方法只需断言异常计数器为 0 即可确认没有线程出现异常。
删除特定环境内容后,我的测试代码的摘录:
const int MaxThreads = 25;
const int MaxWait = 10;
const int Iterations = 10;
private readonly Random random=new Random();
private static int startedThreads=MaxThreads ;
private static int exceptions = 0;
…</p>
[Test]
public void testclass()
{
// Create n threads, each of them will be reading configuration while another one cleans up
Thread thread = new Thread(Method1)
{
IsBackground = true,
Name = "MyThread0"
};
thread.Start();
for (int i = 1; i < MaxThreads; i++)
{
thread = new Thread(Method2)
{
IsBackground = true,
Name = string.Format("MyThread{0}", i)
};
thread.Start();
}
// wait for all of them to finish
while (startedThreads > 0 && exceptions==0)
{
Thread.Sleep(MaxWait);
}
Assert.AreEqual(0, exceptions, "Expected no exceptions on threads");
}
private void Method1()
{
try
{
for (int i = 0; i < Iterations; i++)
{
// Stuff being tested
Thread.Sleep(random.Next(MaxWait));
}
}
catch (Exception exception)
{
Console.Out.WriteLine("Ërror in Method1 Thread {0}", exception);
exceptions++;
}
finally
{
startedThreads--;
}
}
private void Method2()
{
try
{
for (int i = 0; i < Iterations; i++)
{
// Stuff being tested
Thread.Sleep(random.Next(MaxWait));
}
}
catch (Exception exception)
{
Console.Out.WriteLine("Ërror in Method2 Thread {0}", exception);
exceptions++;
}
finally
{
startedThreads--;
}
}
我通过为 nunit 创建一个插件解决了这个问题,它“安装”了一个 ITestDecorator。