views:

327

answers:

2

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

A: 

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

Cornelius
Hi cornelius, thanks for the link. I couldn't understand. Can you please, give me some more details how dispatchertimer helpful in this scenario.
Avatar
I don't think you should use the DispatcherTimer but the link describes the problem in using the timer which is related to the Dispatcher outside a WPF project similar to what you are trying to do
Cornelius
+1  A: 

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.

Steven
Exactly, what I was looking for. Thanks steven great :)
Avatar