【发布时间】:2016-04-18 20:34:29
【问题描述】:
我有一个使用 System.Threading.Timer 的应用程序。当调用 Timer 回调时,我必须在 UI 线程上做一些事情。我使用 MVVMLight DispatcherHelper 来做到这一点。当我运行应用程序时它工作正常,但是当我对它进行单元测试(使用 nUnit)时,DispatcherHelper 不会调用 Action。
为了演示它,我创建了一个简单的单元测试
Timer _Timer; //this is System.Threading.Timer
bool _DispatcherWorks;
[Test]
public async Task MVVMDispatcherTest()
{
DispatcherHelper.Initialize();
Assert.That(DispatcherHelper.UIDispatcher, Is.Not.Null);
_Timer = new Timer(timerCallback, null, 500, 500); //start timer in 0.5 seconds and run every 0.5 seconds
Thread.Sleep(2000); //wait for timer to tick
Assert.That(_DispatcherWorks, Is.True); //will fail
}
private void timerCallback(object state)
{
Console.WriteLine("Timer tick");
Assert.That(DispatcherHelper.UIDispatcher, Is.Not.Null);
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
_DispatcherWorks = true; //this is never called
});
}
我的计时器被执行了 3 次,这是预期的。但是 DispatcherHelper.CheckBeginInvoikeOnUI 中的 Action 不会被调用。谁能建议为什么这不起作用以及如何使其可测试?
【问题讨论】:
标签: c# multithreading unit-testing timer mvvm-light