ユニットテストで重要なイベントを発生させたいのですが。キーが押されたとき、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; } }
}
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>
試験報告書: