Have you noticed the ubiquity of web forms while surfing the internet? Almost every website or web-application you visit leverages web-forms to gain relevant information about yourself. From creating an account over a web-application to filling a brief survey, web forms are everywhere! A form comprises web elements such as checkbox, radio button, password, drop down to collect user data.
If you are going to perform automated browser testing for your website or web-application then you simply can’t afford to drop-out the forms from your test automation scripts. Speaking of test automation, Selenium has an API that helps to find these web elements and take subsequent actions on them like selecting a value or entering some text.
This article will help you understand how you can access forms in Selenium to automate browser testing of your web application. I will be using the JUnit Framework with some annotations to execute our Selenium automation testing later in this article.
To begin our learning with, we’ll first understand what a WebElement is, how can it be accessed in Selenium Automation, and then go about seeing the basic form elements like the input boxes, buttons, the actions that can be performed on these forms and finally writing a script to handle a form and run it on various browsers. If you are already aware of the basics then feel free to skip through the sections according to yourself:
In layman’s language, anything present on a webpage constitutes a WebElement. Examples can be a text box, a radio button, etc. Selenium Webdriver offers an interface called the WebElement which is responsible for all the possible interaction that takes place in a the web page. To find these WebElements, Selenium WebDriver provides 2 methods viz, findElement() and findElements().
findElement(): This method is used to locate a single web element. Once the element is found it is returned as a WebElement object. Let us now see the syntax of findElement(), but before we start using the WebElement object in our test script we need to make note of one very important point.
We need to import below package before we can start creating objects of the WebElements:
import org.openqa.selenium.WebElement;
Syntax for findElement():
WebElement ele = driver.findElement(By.xpath(---xpath---);
findElements(): It returns a list of WebElements that corresponds to the locator defined in the method. The syntax for findElements() is as shown below:
List<WebElement> ele = driver.findElements(By.xpath(---xpath---);
Now that we are thorough with the understanding of the WebElement interface, along with the difference between findElement() & findElements() method in Selenium automation testing.
It is time to deep dive into these web elements. We will now list down all the web fields that may be involved in your website or web-application’s form. We will then notice how to access forms in Selenium WebDriver.
To subsequently build the scripts to access forms in Selenium WebDriver, we need to understand the various fields that we will have to handle in our test automation scripts. Let us try to dig a little more about these WebElements one by one.
Input box is a primary element in any form. No form is complete without user input. It can be of two types:
Here is an image representing the input boxes inside a form.
One of the most important fields to consider while you access forms for Selenium automation testing. There is no point filling up a form if there is no interface to submit the same. Buttons are simply used to submit whatever information we have filled in our text boxes. This can be submitting some form data or simply submitting the sign in information to the server.
In most of the websites that are widely used we see a small box that enables us to check or uncheck it. Mostly in agreement sections wherein the user needs to confirm the understanding of these policies. Checkbox is used to return a boolean value, if it is checked then it would return True else would return false.
Remember seeing a circular element on the screens when we select our Gender in any of the signup forms? That is what a radio button is. It is similar to a checkbox only difference being if we are given multiple radio buttons we can select just one, while in the case of multiple checkboxes, we can opt multiple of them.
We all face the common problem of forgetting our account passwords. Noticed the Forgot Password link on the screens? That is what a link is. It redirects us to a new web page or a new window pop-up or a similar thing. It links us to a new URL altogether.
There are times for a website where there are multiple options for a specific category. Say a website to book your flight tickets. To pick up the Origin & Destination city we often see a list with multiple values. This list which has an arrow at the rightmost end to expand and show the values is called a drop-down. It provides a list of options to the user thereby giving access to one or multiple values as per the requirement.
Below is a snapshot of how Facebook uses forms.
Now that we know what different types of web elements we can come across in our application, We need to identify these web elements through our Selenium automation testing scripts, and to do so we use Selenium locators. Locators are the parameters given to the findElement() or findElements() methods which help to retrieve the web element by using its properties like the ID, Name, Class, etc. In general we have 8 locators in Selenium that are widely used:
Few of the examples are:
WebElement eid = driver.findElement(By.id(“email”);
WebElement pswd = driver.findElement(By.name(“password”);
WebElement sbmtBtn = driver.findElement(By.xpath(“//input[@value=”submit”]”);
In a similar way we can use By.className, By.CSSSelector(), By.linktext(), etc.
Finding these web elements is only half-way of your journey while accessing forms through Selenium automation testing. Now, comes the crux of accessing form in Selenium. Performing actions and interacting with the forms using Selenium.! Let us see how different actions can be performed on each one of them.
1. Input Box
To handle any input box, we must be able to enter information, clear information or get information from the box. Different methods that Selenium offers to work with text boxes are:
To enter text into a textbox we can use the sendKeys method which would input the user required text from our automation script.
driver.findElement(By.id(“username”).sendKeys(“abc@gmail.com”);
The above statement would enter the Email ID as [email protected] into a text box whose ID is username. Now, to clear a pre-entered text or the text that you last entered can be wiped clean with the clear() method.
driver.findElement(By.id(“username”)).clear();
The third method that can be used on a text box is the getText() method. It’ll fetch the text that is written in a text box in case we need to validate some existing or entered text.
String nameText = driver.findElement(By.id(“username”)).getText();
The above line of code would return the text, let us take the text entered by the first line of code above, i.e. [email protected] and store it in nameText variable of string type. There might be chances when the text is present in the value property. In such a scenario we will use the getAttribute() method in place of getText().
String nameText = driver.findElement(By.id(“username”)).getAttribute(“value”);
We can submit the information by using buttons. This can be done though click actions on the same. Below are the methods available in selenium to perform actions on buttons.
It might look like there is no difference in both the methods, but a very minute detail changes the usage of each method. Both of these methods would eventually submit the form data to the server, but we need to understand the type of the web element present. If the element type is either ‘submit’ or ‘button’, click() method would work for both, but if the element type is ‘submit’ with the button being inside
tag, then only submit() would work. If any of the condition is false then submit() won’t work.
Below are the syntax for both:
driver.findElement(By.id(“submtLogIn”).click();
driver.findElement(By.id(“submtLogIn”).submit()
While working with checkbox, we’ll use below Selenium methods:
To select or check a value we use the click() method. It simply changes the state from unchecked to checked and vice-versa.
driver.findElement(By.id(“name”)).click();
Now that we can check/uncheck a checkbox, we might first need to know the state of a checkbox before performing a certain action with Selenium automation testing. To get the state we use isSelected() method which would return a boolean value. This means if the checkbox is checked we’d get a True else we’ll get False.
boolean state = driver.findElement(By.id(“name”)).isSelected();
The actions performed on the radio button are similar to those on a checkbox and we can use the same methods as above for the radio button as well.
Links are generally embedded in a web page for us to navigate to a new screen or a pop up or a form. We can either do a click action on them or can get the text that it holds and then proceed on our execution.
Both of the above methods can be used in a way similar as stated above.
Dropdowns are very common in web applications and are widely used for selecting among a range of options. There is a wide variety of methods that we can use with dropdowns. Let us see them and their corresponding syntax & usage one by one.
In a similar way we can deselect any selected value from the dropdown using any of the below options:
To use any of the above methods in your selenium code, syntax can be as follows:
Select se=new Select(driver.findElement(By.id("nation"))); se.selectByValue("Ind");
There are times while performing Selenium automation testing of our web app, where we need to validate the options coming in our dropdown list, or if we can select multiple options. These are very easily sorted using selenium which gives us the leverage to perform a few more actions. Listed below are a few of them:
To get a list of options we can write our piece of code by referencing a list object:
Select se=new Select(driver.findElement(By.id("nation")));
List<WebElement> list=se.getOptions();
Now that we know the basic operations and handling of Web Elements let us go forward implementing these in a Selenium script. In the next section, I’ll show you a simple program that handles the Form Elements on a demo site.
Now, we will automate the Facebook Sign Up functionality to access form in Selenium, as we perform actions on the web elements. Here is a test script to access forms in Selenium with Java using the JUnit framework.
//Complete code to run the test of facebook sign up
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class TestForms {
static WebDriver driver;
@BeforeClass
public static void setUp(){
System.out.println("-----This is the beginning of our test !!!-----");
System.setProperty("webdriver.chrome.driver", "C:\\Users\\admin\\Downloads\\chromedriver_win32(1)\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://facebook.com");
}
@Test
public void fillForm(){
System.out.println("-----Let us start the sign up process!!!-----");
/*
* Handling text boxes to enter and clear values
*/
WebElement fName = driver.findElement(By.xpath("//input[@name='firstname']"));
fName.sendKeys("--Enter you name here--");
WebElement lName = driver.findElement(By.xpath("//input[@name='lastname']"));
lName.sendKeys("--Enter your last name--");
//Clear the textbox
lName.clear();
lName.sendKeys("XYZ");
WebElement eMail = driver.findElement(By.xpath("//input[@name='reg_email__']"));
eMail.sendKeys("--Enter mail or contact number--");
WebElement pwd = driver.findElement(By.xpath("//input[@name='reg_passwd__']"));
pwd.sendKeys("--Enter a valid password here--");
/*
* Handling dropdown to select date of birth
*/
Select date = new Select(driver.findElement(By.xpath("(id('day'))")));
date.selectByVisibleText("15");
Select month = new Select(driver.findElement(By.xpath("(id('month'))")));
month.selectByVisibleText("Jan");
Select year = new Select(driver.findElement(By.xpath("(id('year'))")));
year.selectByVisibleText("1990");
/*
* Handling Radio buttons to select gender
*/
driver.findElement(By.className("_58mt")).click();
/*
* Handling the Sign Up button to perform click action
*/
WebElement sgnUp = driver.findElement(By.xpath("//button[@id='u_0_13']"));
sgnUp.click();
}
@AfterClass
public static void tearDown(){
System.out.println("-----We're now closing the session...-----");
driver.quit();
}
}
By running the above script, you will be able to access forms in Selenium using the JUnit. If you guys are not familiar with JUnit. Here is an end-to-end guide for running your first Selenium automation testing script with JUnit.
Job well done! However, if you are to access forms in Selenium for your web-application then chances are that your test suites are going to be bigger and complex. You will need to access forms in Selenium on hundreds of browsers + operating systems. Wondering why?
Well, your form may not be as cross browser compatible as you may assume them to be! Here is how a simple DateTime input field may differ in rendering.
Which brings us back to a major question! How do you access forms in Selenium WebDriver over hundred of browsers + OS?
Well, for starters you can go-ahead and set up a Selenium Grid in-house. However, if you are having a bigger test suite, abundant testing requirements then you may have to spend a considerable amount of money and time in order to scale your in-house Selenium Grid. You will need to keep adding the latest device, browsers, operating systems that are being launched to your Selenium Grid. Considering the adoption of Agile, Kanban, and other modern SDLCs(Software Development Life Cycles), the major browser vendors, operating systems are launching a new version every month.
SDLCs(Software Development Life Cycles), the major browser vendors, operating systems are launching a new version every month.
Fortunately, there is a smarter way! Perform your Selenium automation testing on-cloud with LambdaTest.
It offers:
Now, we will run the same Selenium automation testing script over LambdaTest but in parallel.
Let me demonstrate you with a scalable approach to access forms in Selenium. I will be using the online Selenium Grid of LambdaTest to parallely run the above script in different browsers & operating systems. Before we go ahead to run our script on LambdaTest we need to take care of a few points which are listed below:
Since we have already created our script locally, we’ll use the Selenium Desired Capability Generator wherein just by providing some details like the OS, Resolution, Browser(& it’s version),selenium version,location etc, this generator would provide us a few lines of code which would look like below based on our selections.
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.Select;
public class TestForms {
static String username = "Your UserName";
static String accesskey = "Your Access Key";
static RemoteWebDriver driver = null;
static String gridURL = "@hub.lambdatest.com/wd/hub";
boolean status = false;
@BeforeClass
public static void setUp(){
System.out.println("-----This is the beginning of our test !!!-----");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("build", "TestFormsV1.0");
capabilities.setCapability("name", "SeleniumForms");
capabilities.setCapability("platform", "Windows 10");
capabilities.setCapability("browserName", "Chrome");
capabilities.setCapability("version","79.0");
capabilities.setCapability("selenium_version","3.13.0");
capabilities.setCapability("geoLocation","IN");
capabilities.setCapability("chrome.driver","78.0");
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
}
catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
driver.manage().window().maximize();
}
@Test
public void fillForm(){
driver.get("https://facebook.com");
System.out.println("-----Let us start the sign up process!!!-----");
/*
* Handling text boxes to enter and clear values
*/
WebElement fName = driver.findElement(By.xpath("//input[@name='firstname']"));
fName.sendKeys("--Enter you name here--");
WebElement lName = driver.findElement(By.xpath("//input[@name='lastname']"));
lName.sendKeys("--Enter your last name--");
//Clear the textbox
lName.clear();
lName.sendKeys("XYZ");
WebElement eMail = driver.findElement(By.xpath("//input[@name='reg_email__']"));
eMail.sendKeys("--Enter mail or contact number--");
WebElement pwd = driver.findElement(By.xpath("//input[@name='reg_passwd__']"));
pwd.sendKeys("--Enter a valid password here--");
/*
* Handling dropdown to select date of birth
*/
Select date = new Select(driver.findElement(By.xpath("(id('day'))")));
date.selectByVisibleText("15");
Select month = new Select(driver.findElement(By.xpath("(id('month'))")));
month.selectByVisibleText("Jan");
Select year = new Select(driver.findElement(By.xpath("(id('year'))")));
year.selectByVisibleText("1990");
/*
* Handling Radio buttons to select gender
*/
driver.findElement(By.className("_58mt")).click();
/*
* Handling the Sign Up button to perform click action
*/
WebElement sgnUp = driver.findElement(By.xpath("//button[@id='u_0_13']"));
sgnUp.click();
}
@AfterClass
public static void tearDown(){
System.out.println("-----We're now closing the session...-----");
driver.quit();
}
}
You can run the above code directly through Eclipse or through Command Line following the same steps that we have already done earlier. The results would be available in your Lambda Test Dashboard upon execution of the script. I’ll show you the corresponding result page once we execute the script with parallel browsers all at once. Next comes the most interesting part where we can run our tests in parallel browsers without the need of changing the browser details everytime we intend to run our test. But before doing so we will have to create a helper class that will lead the testing. Subsequently, we will have to make a few changes to our main class that contains the test script and we are good to go. In the following part you’ll see our final test script to run our test in parallel on different browsers using Lambda Test.
Test Script Container Class-
The below code would contain the main test script that we intend to execute. This is similar to what has been written above with some minor tweaks in variables. This example shows execution on 3 different browsers. You can modify your script based on your requirement of execution.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.Select;
@RunWith(ParallelHelper.class)
public class TestForms {
static String username = "Your User Name";
static String accesskey = "Your Access Key";
static RemoteWebDriver driver = null;
static String gridURL = "@hub.lambdatest.com/wd/hub";
public static String platform;
public static String browserName;
public static String browserVersion;
boolean status = false;
/*
* Creating parameters for the browsers to be used
*/
@Parameterized.Parameters
public static LinkedList<String[]> getEnvironments() throws Exception {
LinkedList<String[]> env = new LinkedList<String[]>();
env.add(new String[]{"WIN10", "chrome", "79.0"});
env.add(new String[]{"WIN10","firefox","71.0"});
env.add(new String[]{"WIN10","internet explorer","11.0"});
return env;
}
public TestForms(String platform, String browserName, String browserVersion) {
this.platform = platform;
this.browserName = browserName;
this.browserVersion = browserVersion;
}
@Before
public void setUp() {
System.out.println("-----This is the beginning of our test !!!-----");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("build", "TestFormsV1.0"); //Can provide you Build Name
capabilities.setCapability("name", "SeleniumForms"); //Provide your Test Name
capabilities.setCapability("platform", platform); //Would pass the OS to be invoked
capabilities.setCapability("browserName", browserName); //Would pass the Browser name to be invoked
capabilities.setCapability("version", browserVersion); //Would pass the Browser Version to be invoked
capabilities.setCapability("selenium_version", "3.13.0");
capabilities.setCapability("geoLocation", "IN");
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/*
* This is our main test script
*/
@Test
public void fillForm() {
driver.get("https://facebook.com");
driver.manage().window().maximize();
System.out.println("-----Let us start the sign up process!!!-----");
/*
* Handling text boxes to enter and clear values
*/
WebElement fName = driver.findElement(By.xpath("//input[@name='firstname']"));
fName.sendKeys("--Enter you name here--");
WebElement lName = driver.findElement(By.xpath("//input[@name='lastname']"));
lName.sendKeys("--Enter your last name--");
// Clear the textbox
lName.clear();
lName.sendKeys("XYZ");
WebElement eMail = driver.findElement(By.xpath("//input[@name='reg_email__']"));
eMail.sendKeys("--Enter mail or contact number--");
WebElement pwd = driver.findElement(By.xpath("//input[@name='reg_passwd__']"));
pwd.sendKeys("--Enter a valid password here--");
/*
* Handling dropdown to select date of birth
*/
Select date = new Select(driver.findElement(By.xpath("(id('day'))")));
date.selectByVisibleText("15");
Select month = new Select(driver.findElement(By.xpath("(id('month'))")));
month.selectByVisibleText("Jan");
Select year = new Select(driver.findElement(By.xpath("(id('year'))")));
year.selectByVisibleText("1990");
/*
* Handling Radio buttons to select gender
*/
driver.findElement(By.className("_58mt")).click();
/*
* Handling the Sign Up button to perform click action
*/
WebElement sgnUp = driver.findElement(By.xpath("//button[@id='u_0_13']"));
sgnUp.click();
}
@After
public void tearDown() {
System.out.println("-----We're now closing the session...-----");
driver.quit();
}
}
Test Script Helper/Runner Class
This class contains the code that would enable parallel execution of test on different browsers.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;
public class ParallelHelper extends Parameterized {
private static class ThreadPoolScheduler implements RunnerScheduler {
private ExecutorService exec;
public ThreadPoolScheduler() {
String threads = System.getProperty("junit.parallel.threads", "10");
int numThreads = Integer.parseInt(threads);
exec= Executors.newFixedThreadPool(numThreads);
}
public void finished() {
exec.shutdown();
try {
exec.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException exc) {
throw new RuntimeException(exc);
}
}
public void schedule(Runnable childStatement) {
exec.submit(childStatement);
}
}
public ParallelHelper(Class<?> klass) throws Throwable {
super(klass);
// TODO Auto-generated constructor stub
}
}
On running the above class we’ll see that our test runs on the Lambda Test Cloud and the results of the test are generated. Note that you can see the progress on your Eclipse IDE & subsequently the results(like the Execution Video) are available on the Lambda Test Automation Dashboard. Below is a snapshot of how the Execution results would look like in Lambda Test Dashboard:
The Eclipse IDE Console and results on the other hand would show up as below:
I hope this Selenium Java tutorial has helped you access forms in Selenium WebDriver. Remember, forms are fundamental for every business running online. Almost every web application is gathering user information through forms. As an automation tester, you need to ensure two things:
If you aren’t sure about forms being used in your web-application then you can go ahead and leverage an online Selenium Grid such as LambdaTest. Your first 100 automation testing minutes are absolutely free, along with a lifetime free access to our cross browser testing tool. Leverage parallel testing to ensure all your test cycles are delivered on-time. Happy testing!
Previously published at https://www.lambdatest.com/blog/complete-guide-to-access-forms-in-selenium-with-java/