单元测试调用DispatcherHelper.CheckBeginInvokeOnUI的异步方法
本文关键字:异步方法 CheckBeginInvokeOnUI DispatcherHelper 调用 单元测试 | 更新日期: 2023-09-27 18:11:20
我在visual studio 2012中使用MVVM Light 5.2。我的单元测试是MS测试,我不知道如何测试我的异步方法,因为DispatcherHelper没有调用我的Action。使用下面的测试,线程。在调试中永远不会进入休眠状态。
在MVVM光源DispatcherHelper。CheckBeginInvokeOnUi调用UIDispatcher.BeginInvoke(action),什么都不会发生。我做错了什么?
[TestMethod]
public void TestMethod1()
{
DispatcherHelper.Initialize();
TestedMethod();
// Do assert here
}
void TestedMethod()
{
ThreadPool.QueueUserWorkItem((o) =>
{
// Do stuff
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
// Do stuff
Thread.Sleep(1); // Breakpoint here
});
});
}
如果它可以帮助,因为我不想修改MVVM光源,我最后在DispatcherHelper上编写了一个代理,当它在测试方法中初始化时直接调用该操作。它还处理设计模式。
我只需要用UIDispatcher搜索/替换每个DispatcherHelper,就是这样。
下面是代码:public static class UIDispatcher
{
private static bool _isTestInstance;
/// <summary>
/// Executes an action on the UI thread. If this method is called from the UI
/// thread, the action is executed immendiately. If the method is called from
/// another thread, the action will be enqueued on the UI thread's dispatcher
/// and executed asynchronously.
/// For additional operations on the UI thread, you can get a reference to the
/// UI thread's dispatcher thanks to the property GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher
/// </summary>
/// <param name="action">The action that will be executed on the UI thread.</param>
public static void CheckBeginInvokeOnUI(Action action)
{
if (action == null)
{
return;
}
if ((_isTestInstance) || (ViewModelBase.IsInDesignModeStatic))
{
action();
}
else
{
DispatcherHelper.CheckBeginInvokeOnUI(action);
}
}
/// <summary>
/// This method should be called once on the UI thread to ensure that the GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher
/// property is initialized.
/// In a Silverlight application, call this method in the Application_Startup
/// event handler, after the MainPage is constructed.
/// In WPF, call this method on the static App() constructor.
/// </summary>
/// <param name="isTestInstance"></param>
public static void Initialize(bool isTestInstance = false)
{
_isTestInstance = isTestInstance;
if (!_isTestInstance)
DispatcherHelper.Initialize();
}
/// <summary>
/// Resets the class by deleting the GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher
/// </summary>
public static void Reset()
{
if (!_isTestInstance)
DispatcherHelper.Reset();
}
}