How to write a string in textfield which contains underscore in it using TestFX?

3.3k views Asked by At

I am writing a simple login form in JavaFX for which I am writing a test program in TestFX. My TestFX script automatically types the credentials in the textfields and clicks the login button and it works fine further.

But when I want the script to type credentials which contain underscore, it doesn't type the underscore and types until the underscore comes. I have used backslash before underscore but it didn't help me.

Below is a screenshot of my login page.

enter image description here

Below is my test script which works fine when I give string without an underscore.

@Test
public void invalidCredentialsShouldNotLogin()
{
    controller.click("#username").type("invalid");
    controller.click("#password").type("invalid");
    controller.click("#button");

    verifyThat("#welcome", hasText("Login failed"));
}

And this is the script which tries to type a string which contains underscore in it and does not work as intended, and gives exception as invalid key code.

@Test
public void invalidCredentialsShouldNotLogin()
{
    controller.click("#username").type("user_name");
    controller.click("#password").type("invalid");
    controller.click("#button");

    verifyThat("#welcome", hasText("Login failed"));
}

This is the output of the above code.

enter image description here

The same thing happens when I use colon in place of underscore. Please help me fix this. If you require any more information, please tell me. Thanks

1

There are 1 answers

0
Kuldeep Verma On BEST ANSWER

I have got the answer of this question. Actually every special character like underscore or colon has a keycode associated with it. We have to use that keycode to type in the TextField using TestFX script.

In the question above, I wanted to type underscore. Usually when we type underscore, we press two keys together i.e. shift and hyphen (-). Same way we will use the keycodes of these two keys to type underscore using TestFX script.

Below is the code that worked for me and typed underscore in the TextField.

@Test
public void enterCredentialsWithUnderscore()
{
    TextField usernameField = (TextField)GuiTest.find("#username");
    if(username.indexOf("_") != -1)
    {
        String[] tokens = username.split("_");
        for(int i=0; i<tokens.length; i++)
        {
            if (i == 0)
                controller.click(usernameField).type(tokens[i]);
            else
                controller.push(KeyCode.SHIFT, KeyCode.MINUS).type(tokens[i]);
        }
    }
}

KeyCode.MINUS is keycode for hyphen key. And push(KeyCode.SHIFT, KeyCode.MINUS) method pushes the both buttons together thus typing underscore.

Below is a screenshot of the output I received.

enter image description here

Thanks to all.