【问题标题】:Programmatically generate keydown presses for WPF unit tests以编程方式为 WPF 单元测试生成按键
【发布时间】:2010-12-27 09:48:10
【问题描述】:

我正在尝试对 WPF 控件进行单元测试,并且需要模拟按键。我已经看到了一个可能的解决方案here,但是当我尝试传入一个 PresentationSource 时,我不断得到一个空值(来自 PresentationSource.FromVisual() 或 PresentationSource.FromDependencyObject()),这会触发一个异常。

我的问题是如何获得可以在单元测试中使用的非 null PresentationSource?

【问题讨论】:

    标签: c# .net wpf unit-testing wpf-controls


    【解决方案1】:

    您可以像这样扩展 PresentationSource 类:

    public class FakePresentationSource : PresentationSource
    {
        protected override CompositionTarget GetCompositionTargetCore()
        {
            return null;
        }
    
        public override Visual RootVisual { get; set; }
    
        public override bool IsDisposed { get { return false; } }
    }
    

    并像这样使用它:

    var uiElement = new UIElement();
    
    uiElement.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, new FakePresentationSource(), 0, Key.Delete) 
    { 
        RoutedEvent = UIElement.KeyDownEvent 
    });
    

    【讨论】:

      【解决方案2】:

      单元测试的更快解决方案是模拟 PresentationSource 对象。请注意,它需要一个 STA 线程。 示例使用 Moq 和 nunit。

      [Test]
      [RequiresSTA]
      public void test_something()
      {
        new KeyEventArgs(
          Keyboard.PrimaryDevice,
          new Mock<PresentationSource>().Object,
          0,
          Key.Back);
      }
      

      【讨论】:

        【解决方案3】:

        在阅读此post 后想通了。

        基本上,您需要将控件放在 Window 中并在其上调用 Window.Show()。该帖子提到了一个 WPF 错误,但我在 WPF 4 中没有遇到这个问题。

        调用 Window.Show() 后,表示源将不再为空,您将能够向控件发送键。

        【讨论】:

        • 在“CurrentDispatcher”上调用“InvokeShutdown”是在退出时解决“InvalidComObjectException”的缺失环节。感谢您的链接!
        猜你喜欢
        • 2011-06-25
        • 1970-01-01
        • 2011-01-23
        • 2013-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-17
        相关资源
        最近更新 更多