1

我想对我为 Windows 商店项目创建的自定义控件进行单元测试。只是简单的事情,比如“当 X 为真时有一个按钮”。

但是,我似乎什至无法在测试上下文中实例化控件。每当我尝试调用构造函数时,都会收到与未在 UI 上下文中运行相关的异常。我也无法创建针对 Windows 商店项目的编码 UI 测试项目。

  • 如何以编程方式实例化要测试的控件?如何创建 WinRT UI 同步上下文?
  • 如何以编程方式将“用户”命令事件发送到控件?
  • 如何以编程方式实例化/拆卸整个应用程序?
4

1 回答 1

1

我找到了一种使非交互部分工作的hacky方法:使用函数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));
}
于 2012-10-20T07:44:53.407 回答