我想在单元测试中提出一个关键事件。当一个键被按下时,TextBox 应该在它的 text 属性中包含被按下的键。
这是一个使用 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; } }
}
通用的.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>
测试报告: