c# – 单元测试TextBox行为

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

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来引发事件并进一步单元测试行为.

提前致谢.

最佳答案 它可能会迟到,但这是一种单元测试行为的方法,它在调用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);
    }
  }
点赞