我有一个看起来像这样的方法:单元测试方法与本地线程
protected void OnBarcodeScan(BarcodeScannerEventArgs e)
{
// We need to do this on a seperate thread so we don't block the main thread.
ThreadStart starter =() => SendScanMessage(e, _scanDelegates);
Thread scanThread = new Thread(starter);
scanThread.Start();
}
然后线程熄灭,做一些逻辑(和结束调用在我的测试委托)。
我的问题是我的单元测试在线程完成之前完成。所以我的测试失败了。
我可以在System.Threading.Thread.Sleep(1000);
中加上,希望逻辑永远不会超过一秒(它不应该)。但是,这似乎是一个黑客。
问题是我不想将该线程暴露给外部世界甚至是其他课程。
是否有一些很酷的方式来再次找到该线程,并在我的单元测试中等待它?
事情是这样的:
[TestMethod]
[HostType("Moles")]
public void AddDelegateToScanner_ScanHappens_ScanDelegateIsCalled()
{
// Arrange
bool scanCalled = false;
MCoreDLL.GetTopWindow =() => (new IntPtr(FauxHandle));
// Act
_scanner.AddDelegateToScanner(_formIdentity, ((evnt) => { scanCalled = true; }));
_scanner.SendScan(new BarcodeScannerEventArgs("12345678910"));
// This line is fake!
System.Threading.Thread.CoolMethodToFindMyThread().Join();
// Assert
Assert.IsTrue(scanCalled);
}
我明明做了CoolMethodToFindMyThread方法。但是有一些为什么要这样做?
与您提问的问题并不完全相关,但请考虑使用ThreadPool,而不是每次都启动一个新线程。线程启动起来相对昂贵,如果它在一秒钟内终止,让线程池重新使用线程会更有效率。 – 2010-12-02 23:01:30
@David Yaw - 感谢您的提示!我会研究这一点。 – Vaccano 2010-12-03 04:35:52