Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke WPF Dispatcher in Nunit?

I want to test an application which renders a text block with a data field value. I would like to get the actual width and actual height, once the rendering completes. Everything works fine. The problem came first, when I tried to test the application. I'm unable to invoke the dispatcher from the test project.

Following is the code.

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

I've just started using the NUnit. So, please help me.

Thanks

like image 554
Prince Ashitaka Avatar asked Mar 16 '10 05:03

Prince Ashitaka


2 Answers

You might want to look at http://www.codeproject.com/KB/WPF/UnitTestDispatcherTimer.aspx It deals with a DispatcherTimer in WPF and NUnit which in turn uses the Dispatcher.

Edit

From the link try and do this before your test:

Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, testMethod);
// Start the worker thread's message pump
Dispatcher.Run();  // This will block until the dispatcher is shutdown

And stop it after the test.

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);
like image 152
Cornelius Avatar answered Oct 27 '22 20:10

Cornelius


I haven't used nUnit to write unit tests before, but this is a common problem with VS unit tests. What can end up happening is that each test uses a different dispatcher and WPF requires you to use the same dispatcher. To get around this, create a static class to cache the Dispatcher and then invoke everything through it.

like image 22
Steven Avatar answered Oct 27 '22 19:10

Steven