簡體   English   中英

如何為使用Application.Current.Dispatcher.Invoke的方法編寫WPF異步單元測試?

[英]How to write a WPF async unit test for a method that uses Application.Current.Dispatcher.Invoke?

我們有一個用WPF編寫的應用程序。 我正在嘗試為在后台線程上運行的某些代碼編寫單元測試。 在此代碼中的某些地方,我們需要在UI線程上執行操作。 在那些地方,我們使用以下代碼結構:

Application.Current.Dispatcher.Invoke(new Action(() =>
{
// do something on UI thread
}));

當我創建一個異步單元測試時,它似乎卡在了Invoke方法上。 我猜這是因為調度程序不是“調度”。 我試圖通過使用稱為DisaptcherUtil的類來解決此問題,該類在互聯網上的許多地方都被引用了。 但是我無法使它正常工作。 現在,我的代碼的簡化版本如下所示:

    [TestMethod]
    public async Task TestDispatcher()
    {
        new Application();

        DispatcherUtil.DoEvents();

        await Task.Run(() => MethodUsingDispatcher());
    }


    private void MethodUsingDispatcher()
    {
        Application.Current.Dispatcher.Invoke(new Action(() =>
        {
            Console.WriteLine("On the dispatchee thread!");
        }));

        Console.WriteLine("BAck to background trhead");
    }

    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)
        {
            Console.WriteLine("ExitFrame");

            ((DispatcherFrame)frame).Continue = false;
            return null;
        }
    }

當我運行名為“ TestDispatcher”的測試時,它會掛起。

任何人都知道為什么會這樣嗎? 這是執行此操作的正確方法,還是應該改走為我可以在測試中模擬的Dispatcher創建接口的路線。 我已經在某些地方看到了這一點。

我要說的是,您應該將分派隱藏在接口后面,並在單元測試中模擬它:

interface IDispatcher
{
    void Dispatch(Action action);
}

您可以在測試中輕松模擬這一點,並期待那些已調度的調用。

使用真正的調度程序的實現,可以由您的應用程序使用:

public class Dispatcher 
{
    public void Dispatch(Action action)
    {
        Application.Current.Dispatcher.Invoke(action);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM