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

时间:2012-12-12 15:06:43

标签: 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

1 个答案:

答案 0 :(得分:-2)

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

我认为在单元测试中调用按钮单击不是单元测试功能的最佳方法。这是MVVM,MVC,MVP等模式的原因之一。您希望创建一个与UI使用分离的可测试类。 (我道歉,因为我不是故意让它听起来像讲座)。

所以在你的例子中,我要做的是创建一个命令,将它绑定到用法按钮,然后通过调用触发一些可测试组件/部件的命令来进行单元测试。

<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);