如何在Nunit中调用WPF 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。 所以,请帮帮我。

谢谢

我以前没有使用nUnit编写unit testing,但这是VSunit testing的常见问题。 最终可能发生的是每个测试使用不同的调度程序,WPF要求您使用相同的调度程序。 要解决此问题,请创建一个静态类来缓存Dispatcher,然后通过它调用所有内容。

您可能需要查看http://www.codeproject.com/KB/WPF/UnitTestDispatcherTimer.aspx它处理WPF中的DispatcherTimer和NUnit,后者又使用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);