2

我遇到了一些小问题。我想用 Visual Studio 2010 为 c#/wpf/interactivty 项目编写一些单元测试。别忘了我是初学者,很抱歉;)

单元测试应该模拟文本框上的(虚拟)按键事件,结果应该引发一个动作。(动作结果:控制台输出 - 只是作为第一步检查)

我仍然修复了 2 个问题 -> 调度程序问题和presentationSource 错误。

unittest 仍然模拟 keyevent 并且 keyevent 到达了文本框,但问题是,为什么没有通过文本框上的 keydown 事件引发操作?

是线程问题吗?我有什么误解?

这是代码

单元测试
结束时的单元测试你可以检查文本框 - 键盘工作

[TestMethod]
public void simpleTest()
{
    var mockWindow = new MockWindow();

    //simple test to check if the virtualKeyboard works
    string CheckText = "Checktext";

    mockWindow.SendToUIThread(mockWindow.textbox, CheckText);

    mockWindow.SendToUIThread(mockWindow.textbox, "k");

    //needed to start the dispatcher
    DispatcherUtil.DoEvents();
}

调度程序修复

public static class DispatcherUtil
    {
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        public static void DoEvents()
        {
            DispatcherFrame frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }

        private static object ExitFrame(object frame)
        {
            ((DispatcherFrame)frame).Continue = false;
            return null;
        }
    }

我的测试

 class TestAction : TriggerAction<UIElement>
    {
        protected override void Invoke(object parameter)
        {
            Console.WriteLine("testAction invoke");
        }
    }

模拟窗口

public class MockWindow : Window
{
    public TextBox textbox { get; private set; }

    public MockWindow()
    {    
        //add a grid&textbox
        Grid grid = new Grid();
        textbox = new TextBox();

        this.Content = grid;
        grid.Children.Add(textbox);

        //create the testaction/triggerEvent & add them
        TestAction testAction = new TestAction();
        System.Windows.Interactivity.EventTrigger TestTrigger = new System.Windows.Interactivity.EventTrigger();
        TestTrigger.EventName = "KeyDown";
        TestTrigger.Actions.Add(testAction);
        TestTrigger.Attach(this.textbox);
    }

    //enter a keyboard press on an UIElement
    public void SendToUIThread(UIElement element, string text)
    {
        element.Dispatcher.BeginInvoke(new Action(() =>
        {
            SendKeys.Send(element, text);
        }), DispatcherPriority.Input);
    }
}

codeplex sendkeys添加的 MockKeyboard + 用于 unittest 的 PresentationCore 修复(在 SendKeys 类中添加)

public class FixPresentationSource : PresentationSource
{
    protected override CompositionTarget GetCompositionTargetCore()
    {
        return null;
    }

    public override Visual RootVisual { get; set; }

    public override bool IsDisposed { get { return false; } }
}
4

0 回答 0