单元测试TextBox行为

时间:2013-08-29 12:16:42

标签: c# wpf unit-testing textbox behavior

我在单元测试中遇到了麻烦。行为如下:

NumericTextBoxBehavior : Behavior<TextBox>
{
 //handles few events like TextChanged ,PreviewTextInput , PreviewKeyDown , PreviewLostKeyboardFocus 
//to give make it accept numeric values only

}

在进行单元测试时,我编写了这段代码

TextBox textBoxInvoker = new TextBox();
NumericTextBoxBehavior target = new NumericTextBoxBehavior();
System.Windows.Interactivity.Interaction.GetBehaviors(TextBoxInvoker).Add(target);

现在举起我必须致电的事件

textBoxInvoker.RaiseEvent(routedEventArgs)

这个Routed事件args反过来将路由事件作为参数。

请帮助我如何创建模拟RoutedEventArgs以引发事件并进一步单元测试行为。

提前致谢。

1 个答案:

答案 0 :(得分:2)

可能会迟到,但这是一种单元测试行为的方法,它在调用Keyboard Enter时执行命令。

您可以找到更多信息herehere

  [TestFixture]
  public class ExecuteCommandOnEnterBehaviorFixture
  {
    private ExecuteCommandOnEnterBehavior _keyboardEnterBehavior;
    private TextBox _textBox;
    private bool _enterWasCalled = false;


    [SetUp]
    public void Setup()
    {
      _textBox = new TextBox();
      _keyboardEnterBehavior = new ExecuteCommandOnEnterBehavior();
      _keyboardEnterBehavior.ExecuteCommand = new Microsoft.Practices.Composite.Presentation.Commands.DelegateCommand<object>((o) => { _enterWasCalled = true; });
      _keyboardEnterBehavior.Attach(_textBox);
    }

    [Test]
    [STAThread]
    public void AssociatedObjectClick_Test_with_ItemClick()
    {
      _textBox.RaiseEvent(
        new KeyEventArgs(
          Keyboard.PrimaryDevice,
          MockRepository.GenerateMock<PresentationSource>(),
          0,
          Key.Enter) { RoutedEvent = Keyboard.KeyDownEvent });

      Assert.That(_enterWasCalled);
    }
  }