2010-03-16 29 views
6

我想測試一個呈現帶有數據字段值的文本塊的應用程序。一旦渲染完成,我想獲得實際寬度和實際高度。一切正常。當我嘗試測試應用程序時,問題首先出現。我無法從測試項目調用調度程序。如何在Nunit中調用WPF調度程序?

以下是驗證碼。

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。所以,請幫助我。

感謝

回答

1

我以前沒有用過nUnit編寫單元測試,但這是VS單元測試的常見問題。最終會發生什麼是每個測試使用不同的調度程序,WPF要求您使用相同的調度程序。爲了解決這個問題,創建一個靜態類來緩存Dispatcher,然後通過它調用所有的東西。

+0

準確地說,我在找什麼。謝謝史蒂文太棒了:) – 2010-06-10 07:04:08

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

嗨cornelius,感謝您的鏈接。我無法理解。你可以請,給我更多的細節如何dispatchertimer在這種情況下有幫助。 – 2010-03-17 04:03:39

+0

我不認爲你應該使用DispatcherTimer,但是鏈接描述了使用與WPF項目外的Dispatcher相關的計時器的問題,類似於你正在嘗試做的 – Cornelius 2010-03-17 07:32:28