如何在Nunit中调用WPF Dispatcher?

6
我希望测试一款渲染带有数据字段值文本块的应用程序。我想在渲染完成后获得实际宽度和实际高度。一切都很顺利,但问题出现在我尝试测试该应用程序时。我无法从测试项目中调用dispatcher。
以下是代码:
this.Loaded += (s, e) =>
{
    TextBlock textBlock1 = new TextBlock();

    //// Text block value is assigned from data base field.
    textBlock1.Text = strValueFromDataBaseField;        
    //// Setting the wrap behavior.
    textBlock1.TextWrapping = TextWrapping.WrapWithOverflow;
    //// Adding the text block to the layout canvas.
    this.layoutCanvas.Children.Add(textBlock1);

    this.Dispatcher.BeginInvoke(DispatcherPriority.Background,
        (Action)(() =>
            {
                //// After rendering the text block with the data base field value. Measuring the actual width and height.
               this.TextBlockActualWidth = textBlock1.ActualWidth;
               this.TextBlockActualHeight = textBlock1.ActualHeight;

               //// Other calculations based on the actual widht and actual height.
            }
        ));
};

我刚开始使用NUnit,希望你能帮助我。

谢谢

2个回答

2
您可能想要查看http://www.codeproject.com/KB/WPF/UnitTestDispatcherTimer.aspx。它涉及WPF和NUnit中的DispatcherTimer,后者又使用了Dispatcher。请在测试之前尝试进行以下编辑:
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, testMethod);
// Start the worker thread's message pump
Dispatcher.Run();  // This will block until the dispatcher is shutdown

测试结束后请停止它。

Dispatcher disp = Dispatcher.CurrentDispatcher;
// Kill the worker thread's Dispatcher so that the
// message pump is shut down and the thread can die.
disp.BeginInvokeShutdown(DispatcherPriority.Normal);

1

我以前没有用过nUnit编写单元测试,但这是VS单元测试中常见的问题。可能发生的情况是每个测试使用不同的调度程序,而WPF要求您使用相同的调度程序。为了解决这个问题,创建一个静态类来缓存调度程序,然后通过它来调用所有内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接