2010-08-08 30 views
0

我在嘗試將NUnit測試從新線程添加到集合中。這是我正在使用的測試功能:編號爲-1的NUnit錯誤

[Test] 
public void WorkerThreadAccess() 
{ 
    string foo = "Foo"; 
    Collection<string> collection = new Collection<string>(); 
    System.Threading.Thread thread = 
       new System.Threading.Thread(() => collection.Add(foo)); 
    thread.Start(); 

    Collection<string> expected = new Collection<string> { foo }; 
    System.Threading.Thread.Sleep(0); 
    CollectionAssert.AreEqual(expected, collection); 
} 

當我運行測試一次,它通過。然而在不關閉NUnit的GUI每一個後續的測試,NUnit的失敗斷言有一個奇怪的錯誤:

Expected and actual are both <System.Collections.ObjectModel.Collection 1[System.String]`> with 1 elements
Values differ at index [0]
String lengths are both 3. Strings differ at index -1.
Expected: "Foo"
But was: "Foo"

誰能給一些洞察到了什麼錯誤?這些元素對我來說看起來是一樣的,索引-1只應該返回IndexOf()錯誤。

編輯:我使用NUnit 2.5.7

回答

1

嘗試更換 System.Threading.Thread.Sleep(0);thread.Join();

你真正需要的是等待第二個線程來完成,不只是暫停當前的一個。

+0

這就是它(我學到了一種新方法)。你認爲你可以解釋爲什麼如果在一個進程中調用該函數兩次,產生我的線程會導致錯誤? – bsg 2010-08-08 04:28:42

+0

'Sleep(0)'只是將控制權返回給操作系統(或者是處理器?),它從活動線程列表中選擇另一個線程。這並不意味着你的第二個線程將被選中,也不會意味着你的第二個線程在控制返回到主線程時完成了。 爲什麼第二次運行會導致錯誤,但不是第一次?不知道...一些影響第一次執行的資源分配/編譯/巫術魔法開銷可能? 但是很明顯,當'CollectionAssert.AreEqual(expected,collection);'被執行時,你的'collection'仍然被修改。 – 2010-08-08 04:43:36