在单元测试中使用 WPF Dispatcher [英] Using the WPF Dispatcher in unit tests

查看:34
本文介绍了在单元测试中使用 WPF Dispatcher的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让 Dispatcher 运行单元测试时传递给它的委托.当我运行程序时一切正常,但是,在单元测试期间,以下代码将无法运行:

I'm having trouble getting the Dispatcher to run a delegate I'm passing to it when unit testing. Everything works fine when I'm running the program, but, during a unit test the following code will not run:

this.Dispatcher.BeginInvoke(new ThreadStart(delegate
{
    this.Users.Clear();

    foreach (User user in e.Results)
    {
        this.Users.Add(user);
    }
}), DispatcherPriority.Normal, null);

我在我的视图模型基类中有此代码来获取调度程序:

I have this code in my viewmodel base class to get a Dispatcher:

if (Application.Current != null)
{
    this.Dispatcher = Application.Current.Dispatcher;
}
else
{
    this.Dispatcher = Dispatcher.CurrentDispatcher;
}

是否需要为单元测试初始化​​ Dispatcher?Dispatcher 从不运行委托中的代码.

Is there something I need to do to initialise the Dispatcher for unit tests? The Dispatcher never runs the code in the delegate.

推荐答案

通过使用 Visual Studio 单元测试框架,您无需自己初始化 Dispatcher.您说得对,Dispatcher 不会自动处理其队列.

By using the Visual Studio Unit Test Framework you don’t need to initialize the Dispatcher yourself. You are absolutely right, that the Dispatcher doesn’t automatically process its queue.

您可以编写一个简单的辅助方法DispatcherUtil.DoEvents()",它告诉 Dispatcher 处理其队列.

You can write a simple helper method "DispatcherUtil.DoEvents()" which tells the Dispatcher to process its queue.

C# 代码:

public static class DispatcherUtil
{
    [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    public static void DoEvents()
    {
        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
            new DispatcherOperationCallback(ExitFrame), frame);
        Dispatcher.PushFrame(frame);
    }

    private static object ExitFrame(object frame)
    {
        ((DispatcherFrame)frame).Continue = false;
        return null;
    }
}

您也可以在 WPF 应用程序框架 (WAF) 中找到此类>.

You find this class too in the WPF Application Framework (WAF).

这篇关于在单元测试中使用 WPF Dispatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆