1

我想單元測試爲Windows Store項目創建的自定義控件。只是簡單的事情,如「當X爲真時有一個按鈕」。單元測試Windows Store項目中的自定義控件

但是,我似乎無法甚至在測試上下文中實例化控件。每當我嘗試調用構造函數時,都會得到一個與UI上下文中未運行相關的異常。我也無法創建針對Windows Store項目的編碼UI測試項目。

  • 如何以編程方式實例化控件以進行測試?如何創建WinRT UI同步上下文?
  • 如何以編程方式將「用戶」命令事件發送到控件?
  • 如何以編程方式實例化/拆除整個應用程序?

回答

1

我發現了一個非常方便的方法來使非交互式零件起作用:使用函數Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync

很明顯,對嗎?但是,這仍然留下了如何模擬用戶操作的問題。

/// Runs an action on the UI thread, and blocks on the result 
private static void Ui(Action action) { 
    Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
     CoreDispatcherPriority.Normal, 
     () => action() 
    ).AsTask().Wait(); 
} 
/// Evaluates a function on the UI thread, and blocks on the result 
private static T Ui<T>(Func<T> action) { 
    var result = default(T); 
    Ui(() => { result = action(); }); 
    return result; 
} 
[TestMethod] 
public void SliderTest() { 
    // constructing a Slider control is only allowed on the UI thread, so wrap it in UI 
    var slider = Ui(() => new Slider()); 
    var expected = 0; 
    // accessing control properties is only allowed on the UI thread, so same deal 
    Assert.AreEqual(expected, Ui(() => slider.Value)); 
}