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

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

问题描述

我有麻烦的调度运行的委托,我传递给它时,单元测试。一切正常,当我运行程序的很好,但是,一个单元测试以下code将不会运行期间:

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);

我有这个code在我的ViewModel基类来获得一个接线员:

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;
}

有什么我需要做初始化调度单元测试?分派从来没有运行code中的委托。

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单元测试框架,你不需要初始化调度自己。你是绝对正确的,该调度程序不会自动处理它的队列。

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(),它告诉调度员来处理它的队列。

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

C#code:

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调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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