c# - WPF - 在单元测试中引发 KeyEvent 触发器不起作用

标签 c# wpf unit-testing controls keyevent

我想在单元测试中提出一个关键事件。按下某个键时,TextBox 应在其文本属性中包含按下的键。

这是一个使用 Xunit 的最小工作示例:

[TemplatePart(Name = Field0Name, Type = typeof(TextBox))]
class MyControl : Control
{
    public const string Field0Name = "Field0";
}

public class MyControlTests
{
    private MyControl control;
    public MyControlTests()
    {
        MemoryStream ms = new MemoryStream();
        StreamWriter sw = new StreamWriter(ms);
        sw.Write(@"<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                        <Grid>
                            <TextBox Name='Field0'/>
                        </Grid>
                    </ControlTemplate>");
        sw.Flush();
        ms.Position = 0;

        control = new MyControl() { Template = (ControlTemplate)XamlReader.Load(ms) };
        control.ApplyTemplate();
    }

    [Fact]
    public void Field0Name_PreviewKeyDownEvent_WriteLetter()
    {
        TextBox tb = (TextBox)control.Template.FindName(MyControl.Field0Name, control);
        FocusManager.SetFocusedElement(control, tb);

        tb.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, new FakePresentationSource(), Environment.TickCount, Key.A)
        {
            RoutedEvent = TextBox.PreviewKeyDownEvent
        });

        Assert.Equal("a", tb.Text);
    }
}

public class FakePresentationSource : PresentationSource
{
    protected override CompositionTarget GetCompositionTargetCore()
    {
        return null;
    }

    public override Visual RootVisual { get; set; }

    public override bool IsDisposed { get { return false; } }
}

Generic.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TextBoxRaiseEventProject">
<Style TargetType="{x:Type local:MyControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <Grid>
                        <TextBox x:Name="Field0"/>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

测试报告:

test report

最佳答案

对于您的问题,此回复不是您所希望或可能一直期待的。但我认为它是成立的,我希望您在阅读后重新考虑您的单元测试方法。

我认为在单元测试中调用按钮单击并不是对功能进行单元测试的最佳方法。这是 MVVM、MVC、MVP 等模式的原因之一。您想创建一个与 UI 使用分开的可测试类。 (我很抱歉,因为我不想让它听起来像一场讲座)。

因此,在您的示例中,我要做的是创建一个命令,将其绑定(bind)到按钮以供使用,然后通过调用将触发一些可测试组件/部分的命令来进行单元测试。

<Button Command="{Binding PushButtonCommand}"..

some class MyClass
{
    public ICommand PushButtonCommand
    {
        get
        {
           return _pushButtonCommand ??
                (_pushButtonCommand = new DelegateCommand(ExecutePushButton));
        }
     }

    private void ExecutePushButton()
    {
         //lets pretend it sets some property that you need to test;
         NeedBacon = true;   
    }

现在这是可以测试的了。在创建类后的单元测试中,触发命令 并检查属性:

Assert.IsFalse(myClassInstance.NeedBacon);
((DelegateCommand)myClassInstance.PushButtonCommand).Execute(null);
Assert.IsTrue(myClassInstance.NeedBacon);

关于c# - WPF - 在单元测试中引发 KeyEvent 触发器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13842588/

相关文章:

c# - 在我的 C# XAML Windows 8.1 应用程序中,如何进行编程绑定(bind)?

c# - sourceupdated 事件未触发

android - ProviderTestCase2.getProvider() 为空

unit-testing - 我应该如何组织我的单元和集成测试?

javascript - 正则表达式:字符集验证

C# JsonConvert 使用默认转换器而不是自定义转换器

c# - 自承载 WCF 服务 : How to access the object(s) implementing the service contract from the hosting application?

c# - WPF System.OutOfMemoryException 系统.Windows.Automation.Peers.AutomationPeer.UpdateSubtree

javascript - Sinon如何对异步函数进行单元测试的 stub 方法

c# - 如何用另一个字符串拆分字符串