Complete Guide To Access Forms In Selenium With Java
Complete Guide To Access Forms In Selenium With Java
This article will help you understand how you can access forms in Selenium to automate browser testing of your web application.
Join the DZone community and get the full member experience.Join For Free
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.
You may also like: How To Test a Login Process With Selenium and Java
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:
What Is A WebElement?
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 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:
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() and 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 form. We will then notice how to access forms in Selenium WebDriver.
Types Of Fields To Access In Forms With Selenium
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.
The input box is a primary element in any form. No form is complete without user input. It can be of two types:
- Text Field Box – Text boxes that display the value as is entered by the user.
- Password Field Box – Text boxes that display special characters (mostly ‘*’) when the value is entered by the user.
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 in 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 of 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.
How To Web Elements In A Form With Selenium?
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 eight locators in Selenium that are widely used:
- Tag Name
- Class Name
- Partial LinkText
- CSS Selector
Few of the examples are:
In a similar way we can use By.className, By.CSSSelector(), By.linktext(), etc.
Interacting With Web Elements By Accessing Forms In Selenium
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.
The above statement would enter the Email ID as email@example.com 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.
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. firstname.lastname@example.org 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 conditions is false then submit() won’t work.
Below is the syntax for both:
3. Check Box
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.
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();
4. Radio Button
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 with 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 and usage one by one.
- selectByVisibleText(String) — It selects the option by comparing the visible text wherein String value passed in the method is what is compared.
- selectByIndex(int) — Selects option based on the index in the drop-down menu with integer parameter passed as the index.
- selectByValue(String) — Selects the option based on the option value in string format
In a similar way we can deselect any selected value from the dropdown using any of the below options:
- deSelectAll() — This would deselect all the options selected from a dropdown.
To use any of the above methods in your selenium code, syntax can be as follows:
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:
- getAllSelectedOptions() — We may come across dropdowns wherein we can select multiple options. Now, to get the list of all the selected options we can use this method.
- getFirstSelectedOption() — This method would return the first option that has been selected from the dropdown and unlike the above method it would return a single web element and not a list.
- getOptions() — This method would enable us to get a list of all available options in a dropdown.
- isMultiple() — To check if a dropdown can take multiple options, we can use isMultiple() method which would return a boolean value.
To get a list of options we can write our piece of code by referencing a list object:
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.
Handling Form Elements Through Selenium WebDriver
Now, we will automate the Facebook Sign Up functionality to access the 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.
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.
Thoughts About Scalability For A Faster Test Cycle?
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.
Access Forms In Selenium Grid On-Cloud
Let me demonstrate to you a scalable approach to access forms in Selenium. I will be using online Selenium Grid of LambdaTest to parallelly 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:
- Instead of invoking the regular FirefoxDriver, we’ll have to use the Remote WebDriver along with the capabilities related to the browser, its version, OS, etc.
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.
- Now we just need to declare the LambdaTest authentication credentials in the Selenium automation testing scripts. That way, the WebDriver would know the correct Hub URL it needs to address. Below is the final script that we will be using to run our tests on LambdaTest. The changes to our existing script are highlighted.
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 the 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 every time 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.
Test Script Helper/Runner Class
This class contains the code that would enable parallel execution of test on different browsers.
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:
Were You Able To Access Forms In Selenium WebDriver?
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:
- All your forms are functionally working as they should.
- All your forms are cross-browser compatible so they are accessed by every customer.
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 lifetime free access to our cross-browser testing tool. Leverage parallel testing to ensure all your test cycles are delivered on-time. Happy testing!
Published at DZone with permission of Aditya Dwivedi . See the original article here.
Opinions expressed by DZone contributors are their own.