我目前正在尝试寻找解决方案,如何确保在测试方法产生的线程中发生异常时测试失败。运行多线程nunit测试的最佳方式
我不想在单元测试中开始讨论多个线程。 =>“单元测试”。替换(“单元”,“集成”);
我已经在几个论坛上看过很多帖子,我知道的关于CrossThreadTestRunner,但是我正在寻找一种解决方案,它集成到nunit中,并且不需要重写很多测试。
我目前正在尝试寻找解决方案,如何确保在测试方法产生的线程中发生异常时测试失败。运行多线程nunit测试的最佳方式
我不想在单元测试中开始讨论多个线程。 =>“单元测试”。替换(“单元”,“集成”);
我已经在几个论坛上看过很多帖子,我知道的关于CrossThreadTestRunner,但是我正在寻找一种解决方案,它集成到nunit中,并且不需要重写很多测试。
我通过为nunit创建插件来解决问题,该插件“安装”ITestDecorator。
非测试线程(即其他衍生线程)上的异常不会导致测试失败的原因是NUnit默认配置为使用legacyUnhandledExceptionPolicy这是一个可以通过应用程序应用的.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;
...
[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--;
}
}
这是怎样的答案? – Induster 2015-01-06 22:53:18
请你可以进一步解释这是如何解决你的问题? – Holf 2015-02-05 15:33:39