Testing UI / set focus on TextBox

2k views Asked by At

I have a problem with testing the value of a TextBox. First of all i show you the code of the testcase:

[TestCase]
public void trage_kilogramm_ein()
{
    var windowPeer = new FrameworkElementAutomationPeer(this.zieleTest);
    var liste = windowPeer.GetChildren();
    var boxPeer = (TextBoxAutomationPeer)liste[34];
    boxPeer.VerifyAccess();
    var buttonPeer = (ButtonAutomationPeer)liste[9];
    var button = (Button)buttonPeer.Owner;
    var box = (TextBox)boxPeer.Owner;
    box.Visibility = Visibility.Visible;
    box.VerifyAccess();
    box.Focus();
    testWindow.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action    (boxPeer.SetFocus));
    var args = new RoutedEventArgs(Button.ClickEvent, button);
    button.RaiseEvent(args);
    Assert.AreEqual("8", ((IValueProvider)boxPeer).Value);
}

I have a window with 10 TextBoxes where you can put values in. I also have 10 Buttons for the numbers from 0 to 9 which just send key events for a specific number. In the code i simulate the click event for the number/button "8". My problem is that i can`t set the focus onto the TextBox. My test always fails because the "TextBox.Text" is still "String.Empty" and does not get the value "8".

Thanks.

// EDIT: Okay, now i get the focus. It seemed that I needed to set the focus on the parent. I wrote two Methods to see if I get the KeyboardFocus.

private void Gewicht_obere_OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    Console.WriteLine("Got Focus");
}

private void Gewicht_obere_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    Console.WriteLine("Focus Lost");
}

The problem is now i get the focus but i lost it immediately.

1

There are 1 answers

0
Sajeetharan On BEST ANSWER

Get the reference for the specific control(in that case TextBox).

Dispatcher.BeginInvoke((ThreadStart)delegate
            {
                control.Focus();
            });