【问题标题】:Unit testing a custom control in a windows store project在 Windows 商店项目中对自定义控件进行单元测试
【发布时间】:2012-10-10 15:18:33
【问题描述】:

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

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

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

【问题讨论】:

    标签: visual-studio unit-testing windows-runtime windows-store-apps ui-testing


    【解决方案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));
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2011-10-02
      相关资源
      最近更新 更多