我目前正在嘗試尋找解決方案,如何確保在測試方法產生的線程中發生異常時測試失敗。運行多線程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