Selenium: clear and type

By: Slav Kurochkin

In this post I'm writing about how to abstract repetitive Selenium calls and make your testing a bit more clean.

When I see some kind of form, first thing to do is clear the input field, make sure that nothing unexpected been populated to the field. And after everything was cleared you can continue working with it, for example leave empty or type some text in it. Here is how you would do it normally using PageFactory:

@FindBy(how = How.ID, using = "username")
public WebElement userName;

@FindBy(how = How.ID, using = "password")
public WebElement passwordField;


@Test
public void loginTest(){

userName.clear();
userName.sendKeys("some_user_name")

passwordField.clear();
passwordField.sendKeys("some_password")
}

Even though it is ok for small form, but what if you have larger form, lets say with more then 20 input fields in it. Well, clearing and typing need to be abstracted.
Here is how you do it:

First abstract .clear and .sendKeys, put them in one method and then call it within your parameters:


@FindBy(how = How.ID, using = "username")
public WebElement userName;

@FindBy(how = How.ID, using = "password")
public WebElement passwordField;


@Test
public void loginTest(){

clearAndType(userName ,"some_user_name")
clearAndType(passwordField, "some_password")

}


public void clearAndType(WebElement element, String text){
element.clear
element.sendKeys(text);
}

What is the benefit of it? Easy to understand what is going on and maintain. Isn't it nice and elegant? ๐Ÿ™‚

View Comments

Leave a Comment

Use markdown or basic HTML and be nice.