2016-10-04 675 views
1

我在Visual Studio 2012中使用MVVM Light 5.2。我的單元測試是MS測試,我無法計算如何測試我的異步方法,因爲DispatcherHelper沒有調用我的行動。 使用以下測試,調試中永遠不會到達Thread.Sleep。單元測試調用DispatcherHelper.CheckBeginInvokeOnUI的異步方法

在MVVM光源DispatcherHelper.CheckBeginInvokeOnUi調用UIDispatcher.BeginInvoke(action),並且不會發生任何事情。 我在做什麼錯?

[TestMethod] 
    public void TestMethod1() 
    { 
     DispatcherHelper.Initialize(); 
     TestedMethod(); 
     // Do assert here 
    } 

    void TestedMethod() 
    { 
     ThreadPool.QueueUserWorkItem((o) => 
     { 
      // Do stuff 
      DispatcherHelper.CheckBeginInvokeOnUI(() => 
      { 
       // Do stuff 
       Thread.Sleep(1); // Breakpoint here 
      }); 
     }); 
    } 

回答

1

如果它可以幫助,因爲我不希望修改MVVM光源,我終於寫了一篇關於DispatcherHelper代理時,它在測試方法進行初始化,直接調用操作。它也處理設計模式。

我必須通過UIDispatcher搜索/替換每個DispatcherHelper,就是這樣。

這裏是代碼:

public static class UIDispatcher 
{ 
    private static bool _isTestInstance; 

    /// <summary> 
    ///  Executes an action on the UI thread. If this method is called from the UI 
    ///  thread, the action is executed immendiately. If the method is called from 
    ///  another thread, the action will be enqueued on the UI thread's dispatcher 
    ///  and executed asynchronously. 
    ///  For additional operations on the UI thread, you can get a reference to the 
    ///  UI thread's dispatcher thanks to the property GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher 
    /// </summary> 
    /// <param name="action">The action that will be executed on the UI thread.</param> 
    public static void CheckBeginInvokeOnUI(Action action) 
    { 
     if (action == null) 
     { 
      return; 
     } 
     if ((_isTestInstance) || (ViewModelBase.IsInDesignModeStatic)) 
     { 
      action(); 
     } 
     else 
     { 
      DispatcherHelper.CheckBeginInvokeOnUI(action); 
     } 
    } 

    /// <summary> 
    ///  This method should be called once on the UI thread to ensure that the GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher 
    ///  property is initialized. 
    ///  In a Silverlight application, call this method in the Application_Startup 
    ///  event handler, after the MainPage is constructed. 
    ///  In WPF, call this method on the static App() constructor. 
    /// </summary> 
    /// <param name="isTestInstance"></param> 
    public static void Initialize(bool isTestInstance = false) 
    { 
     _isTestInstance = isTestInstance; 
     if (!_isTestInstance) 
      DispatcherHelper.Initialize(); 
    } 

    /// <summary> 
    /// Resets the class by deleting the GalaSoft.MvvmLight.Threading.DispatcherHelper.UIDispatcher 
    /// </summary> 
    public static void Reset() 
    { 
     if (!_isTestInstance) 
      DispatcherHelper.Reset(); 
    } 
}