我有一個問題單元測試一個線程啓動並完成時觸發事件的類。違規源的削減版本如下:單元測試線程事件觸發
public class ThreadRunner
{
private bool keepRunning;
public event EventHandler Started;
public event EventHandler Finished;
public void StartThreadTest()
{
this.keepRunning = true;
var thread = new Thread(new ThreadStart(this.LongRunningMethod));
thread.Start();
}
public void FinishThreadTest()
{
this.keepRunning = false;
}
protected void OnStarted()
{
if (this.Started != null)
this.Started(this, new EventArgs());
}
protected void OnFinished()
{
if (this.Finished != null)
this.Finished(this, new EventArgs());
}
private void LongRunningMethod()
{
this.OnStarted();
while (this.keepRunning)
Thread.Sleep(100);
this.OnFinished();
}
}
然後我有一個測試,以檢查LongRunningMethod
後Finished
事件觸發完成如下:
[TestClass]
public class ThreadRunnerTests
{
[TestMethod]
public void CheckFinishedEventFiresTest()
{
var threadTest = new ThreadRunner();
bool finished = false;
object locker = new object();
threadTest.Finished += delegate(object sender, EventArgs e)
{
lock (locker)
{
finished = true;
Monitor.Pulse(locker);
}
};
threadTest.StartThreadTest();
threadTest.FinishThreadTest();
lock (locker)
{
Monitor.Wait(locker, 1000);
Assert.IsTrue(finished);
}
}
}
這樣的想法在這裏因爲測試會阻止最多1秒 - 或者直到Finish
事件被觸發 - 在檢查finished
標誌是否被設置之前。
很明顯,我做了一些錯誤的事,因爲有時測試會通過,有時不會。調試似乎非常困難,以及我預計會遇到的斷點(例如OnFinished
方法)似乎並不總是如此。
我假設這只是我對線程工作方式的誤解,所以希望有人能夠啓發我。
感謝所有的答覆。我還通過使線程工作者方法(即LongRunningMethod)在啓動時將其設置爲自己的控制標記來引入另一個錯誤。今天肯定是如何在你的代碼中引入競爭條件的速成班,doh! – Dougc