Every few weeks, new features are added to web applications for higher user engagement. Automated testing is necessary to test new features and ensure that the UI is working well. Selenium is one of the popular Automation Testing Tools.
Selenium is an open-source automation testing tool that supports a number of scripting like C#, Java, Perl, Ruby, JavaScript, etc. Depending on the application to be tested, one can choose the script accordingly.
Java is a popular language for scripting with 30.3% of the developers using it, as suggested by the StackOverflow 2024 annual survey.
This article helps you understand how to perform Automated Testing using Selenium Javascript from basics using simple example.
Get Started with Selenium Automation Framework in Java
To learn Selenium with Java, one must combine the different components to start coding.
- Preferred for automated functional testing
- Compatible with multiple operating systems like Windows, Linux, Solaris, and macOS
- Supports multiple browsers like Chrome, Safari, IE, Edge, and Firefox
- Easy to integrate with Jenkins, Maven, and Docker to achieve a continuous testing approach.
- Tools like TestNG and JUnit further help structure the Selenium tests for easy maintainability and generating reports.
This section teaches how to set up and run a simple test through Selenium with Java bindings.
Pre-requisites for Setup and Configuration of Selenium in Java
The following components will get started with Java to run Automated Tests:
- Install Java (JDK)
- Install Eclipse
- Selenium Client and WebDriver Language bindings
- Configuring Selenium Webdriver with Eclipse
- Creating and Running the first test with Selenium and Java
Step 1 – Install Java
- A Java development kit that includes the JRE (Java Runtime Environment) is required to write and run Java programs. JRE is a child of JDK, which comes along with JDK installation.
- Even for running applications that need the dependency of Java, one needs to install JDK.
- One such application is Eclipse IDE. Download Java, install it, and set the environment path.
- Once the path is set, verify the installation by typing java -version on the command prompt, which provides the details of the installed java version.
Step 2 – Install Eclipse
Eclipse is a Java development platform for writing and running code.
- Download Eclipse from their office page. Based on the OS, one can go with the required option.
- Once downloaded, extract the downloaded file. Once completed, one can see the eclipse .exe in the eclipse folder:
Read More: How to configure Selenium in Eclipse
Step 3 – Selenium Client and WebDriver Language Bindings
Selenium Webdriver supports multiple , and each language has its client driver. As we are using Selenium with Java, we need to have Selenium Java Client Driver. One can download the client driver from the official Selenium website and check the multiple language client drivers provided.
Once downloaded, extract the contents of the downloaded file and then move to the next step, configuring Selenium Webdriver with Eclipse.
Step 4 – Configuring Selenium WebDriver With Eclipse
This is a vital step of starting with Selenium. To configure Eclipse with the Selenium Webdriver client,
- Double-click on the eclipse.exe file to launch it
- Create a workspace Think of it just like any other folder, which stores all the scripts in one place. One can choose to create as many workspaces as required. Click on Launch to launch the workspace.
- Create a new Java project by clicking on File-> New-> Java Project and name the project
- Create a package under this project by right-clicking on the ‘src’ folder
- Once the package is created, right-click on the package and create a class. Once the class is created, go ahead with adding the Selenium Jars to the project.
- To add the Selenium Jars, right-click on the project folder and go to Properties:
From the Properties window, navigate to ‘Java Build Path’ and click on ‘Add External JAR’s
Add the downloaded Selenium Jars and click on ‘Apply and Close.’ Selenium with Eclipse is configured now. Now Eclipse is ready to execute the first script.
Step 5 – Creating and Running the first test using Selenium and Java
- As the first test, we will write a script to open ‘google.com’ on the Chrome browser.
- To use Chrome, it is mandatory to have the driver executable. To download the driver executable, visit the Selenium website.
- One can download the executable file for specific browsers in the third-party driver browser section.
Post downloading, below is the code snippet to run the first test using Selenium and Java:
import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class FirstTestInSelenium { public static void main(String[] args) { // TODO Auto-generated method stub //setting the driver executable System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe"); //Initiating your chromedriver WebDriver driver=new ChromeDriver(); //Applied wait time driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //maximize window driver.manage().window().maximize(); //open browser with desried URL driver.get("https://www.google.com"); //closing the browser driver.close(); } }
In the code snippet above, we have used the Selenium keyword driver.get(“URL to open in browser”) to open URL in the desired browser. Other keywords like driver.close help to close the browser window as a cleanup part.
This was a quick starter to learn Selenium with Java and run Automated Tests. One should also consider the best practices while writing Selenium tests.
Selenium Java Resources
- How to configure Selenium in Eclipse
- Maven Dependency Management with Selenium
- Locators in Selenium: A Detailed Guide
- Selenium Commands every Developer or Tester must know
- Selenium WebElement Commands
- Desired Capabilities in Selenium Webdriver
- Assert and Verify Methods in Selenium
- Select Class in Selenium : How to select a value in dropdown list?
- SendKeys in Selenium WebDriver
- Handling Login Popups in Selenium WebDriver and Java
- How to Launch Browser in Selenium
- How to handle Alerts and Popups in Selenium?
- How to Find Element by Text in Selenium: Tutorial
- How to perform UI Testing with Selenium
- Regression Testing with Selenium: Tutorial
- Cross Browser Testing in Selenium : Tutorial
- Page Object Model and Page Factory in Selenium
- How to handle Action class in Selenium
- How to run your first Selenium test script
- Parallel Testing with Selenium
- JUnit Testing Tutorial: JUnit in Java
- All about TestNG Listeners in Selenium
Best Practices while writing Selenium tests with Java
Some of the essential aspects to remember while writing Selenium tests with Java are:
- Using the Right Locator
Selecting locators are the building blocks of a Selenium script, and using the right one is critical. If incorrect locators are used, they tend to make the script flaky and unreliable. Using ‘ID’ and ‘Name’ locators is easy. They also provide faster execution and are more reliable than CSS and XPath.
Read More: Quick XPath Locators Cheat Sheet
- Incorporate the Test-Driven Script
When we talk about testing, it is about testing the software on multiple permutations and a combination of data. The same should be incorporated into the Selenium tests. Multiple data points should drive all Selenium tests, and a data-driven framework helps achieve this.
- Using the right Wait
For WebElements or a page to load, it is essential to give a specific halt time to the script and avoid failure. Selenium provides certain waits like ‘Implicit’ or ‘Explicit’ to achieve this. Both these waits halt the execution of the script until it finds the element.
The moment it finds the element, it continues the execution of the script. ‘Thread.sleep’, on the other hand, stops the execution for the defined period even when it finds the element in the defined interval. This increases the execution time of the script.
- Don’t make scripts specific to a Browser or Driver
Cross browser testing plays a vital role in testing. Depending on business needs, one may expect the scripts to run on multiple browsers or a specific browser. Selenium frameworks like TestNG provide annotations like @parameters, and JUnit provides annotations like @RunWith, which helps run tests on multiple browsers and corresponding drivers.
- Validate Tests using Assertions
The key to writing a good test is validating the tests. Just like when one writes a test case and mentions the actual and expected results, one needs to assert the tests in Selenium with the help of assertions provided in frameworks like TestNG and JUnit. If the assertions are not used, the testing process is incomplete, as it does not validate the test build’s correctness.
- Take Screenshots for Reporting
As a QA tester, it is essential to provide proof of testing for failures with supportive screenshots. The same stands for Automated Selenium testing. In case a test fails, it is vital to have corresponding screenshots. This helps explain the bug to the developer, who can debug it instantly.
Similarly, from a reporting perspective, to provide insight to the stakeholders, it is valuable to share reports with them, to establish the stability of the product. For this, Selenium provides a default reporting system with frameworks like TestNG and provides further customizations to them using TestNG listeners.
Read More: Top 5 Selenium Reporting Tools
Why run Selenium Java Tests on BrowserStack Real Device Cloud?
You should run Selenium Java Tests on a real device cloud like BrowserStack Automate for below reasons:
- Realistic Testing Conditions: Real device clouds provide access to a broad spectrum of devices and environments, ensuring tests reflect actual user conditions accurately.
- Enhanced Security: Maintained with high security standards, real device clouds offer secure, isolated testing environments, minimizing data breach risks.
- Broad Browser and OS Coverage: Helps identify compatibility issues across various browsers and operating systems, enhancing user experience.
- Performance Insights: Real devices yield authentic performance data essential for optimizing application responsiveness.
- Scalability and Accessibility: Facilitates scalable and accessible testing, suitable for distributed teams.
- CI/CD Integration: Integrates smoothly with CI/CD pipelines for continuous testing and early issue detection.
- Cost-Effectiveness: Although initially more costly, it saves on long-term expenses related to fixes and support.
Conclusion
Selenium WebDriver has made automation testing easier and more efficient than ever. By using JavaScript to create test scripts, it is easy to perform automated UI Testing for applications. This is useful especially when development cycles are short and the features have to be added every few weeks to keep up with the users’ demand.
Selenium is widely recommended due to the flexibility it offers. It supports major platforms like Windows, Linux, etc., and browsers like Chrome, IE, Edge, Firefox, and Safari. Learning Selenium with Java optimizes testing, especially in regression and cross-browser testing.
With multiple plugins making their way into Selenium, it has resulted in making testing effortless and less time-consuming. Continuous Integrations with Jenkins and Maven have led to continuous testing models.
To create an application with the optimal user experience, use cloud-based Automation Selenium Testing tools like BrowserStack that offers access to 3500+ real browsers and devices to test on. Test on a real device cloud to offer a seamless cross-platform experience through accurate testing. Since testing on Cloud Selenium Grid takes real user conditions into account, it helps identify the bottlenecks and deliver a seamless and consistent user experience across different browsers and devices.