4

我在对我写的行为进行单元测试时遇到了麻烦。行为如下:

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

提前致谢。

4

1 回答 1

2

可能为时已晚,但这是一种对在调用键盘输入时执行命令的行为进行单元测试的方法。

您可以在此处此处找到更多信息

  [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);
    }
  }
于 2014-04-27T23:08:03.580 回答