内容简介:我有一个问题单元测试一个类,当一个线程启动并完成时会触发事件.违规来源的简化版本如下:然后我进行了测试,检查LongRunningMethod完成后Finished事件是否触发,如下所示:所以这里的想法是在检查是否设置完成标志之前,测试将阻塞最多一秒 – 或者直到Finish事件被触发.
我有一个问题单元测试一个类,当一个线程启动并完成时会触发事件.违规来源的简化版本如下:
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);
}
}
}
所以这里的想法是在检查是否设置完成标志之前,测试将阻塞最多一秒 – 或者直到Finish事件被触发.
显然,我做错了,因为有时测试会通过,有时则不会.调试似乎非常困难,而且我期望被击中的断点(例如OnFinished方法)似乎并不总是如此.
我假设这只是我对线程工作方式的误解,所以希望有人可以启发我.
以上所述就是小编给大家介绍的《c# – 单元测试从线程触发的事件》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Modeling the Internet and the Web
Pierre Baldi、Paolo Frasconi、Padhraic Smyth / Wiley / 2003-7-7 / USD 115.00
Modeling the Internet and the Web covers the most important aspects of modeling the Web using a modern mathematical and probabilistic treatment. It focuses on the information and application layers, a......一起来看看 《Modeling the Internet and the Web》 这本书的介绍吧!