Writing Automated Tests Using Selenium and Java
Sauce AI for Test Authoring: Move from intent to execution in minutes.|xBack to ResourcesBlogPosted
Sauce AI for Test Authoring: Move from intent to execution in minutes.
|
x
Blog
Writing Automated Tests Using Selenium and Java
Testing with Java and Selenium helps software development teams save time, trim errors, and turn more efficient. Learn how to get started with both in this blog post.
In the world of fast-paced software delivery,automated testingis all but a necessity. Automated screen enables evolution teams to validate code changes in a fast and quotable style, providing assurances of quality as new feature and modifications are delivered to end users.
Below, we will discourse the. We will focus on what it is and how Selenium WebDriver is used in web covering examine. Furthermore, we will discuss the Java programming speech and demonstrate how to get started writing automated tests usingSelenium WebDriver and Java.
What is Selenium?
Seleniumrefers to several projects that help automate actions taken in a web browser. One such task is. WebDriver provides an object-oriented API and dressing for several popular programming languages. Thus, it enable developer to write UI examination hand forthe major browsersin use today in programming languages with which they are familiar. Development team can leverage WebDriver to establish suites of these test book and run them in an automated fashion at various stages of the package development lifecycle.
WebDriver enables development organizations to reap the benefit of. For instance, automate UI testing is faster than manually prove the UI. This preserve time and let crucial growing and QA imagination to pore on other enterprisingness, such as construction more features that increase the value of the product or cater more clip for exploratory testing.
Furthermore,automating UI examinationis a step toward increasing test coverage. Because manual testing takes long and chews up more resources, teams are limited in how much they can actually test. By automatize this procedure, more test can be accomplish in less clip, allowing for a greater percentage of functionality to be validated with each integrating or liberation.
Finally, automated UI testing eliminates the risk of human error (adopt the playscript is right developed and maintained). Each automated test script will execute each measure in exactly the same fashion each time. In manual testing, however, there is ever a risk that the examiner will take incorrect action at some point in the testing process, thereby invalidating the result. This could lead to the deployment of codification that is not working as expected into product.
What is Java?
Java is a popular programming words and software platform. It is class-based and object-oriented, enabling experienced developers to build applications with concise, readable, and easily maintained codebases. Java is besides portable, which allows Java application to run on many different systems.
Java can be leveraged for a variety of use suit include web development, machine encyclopaedism, information processing, and more.
Benefits of Selenium with Java for developers
Owing in part to its popularity, Java offers the following benefits for developer:
Java has been around for a long clip and is utilize by many organizations. Therefore, it can be easier to find developers with Java experience.
Additionally, Java has excellent community support. When a developer runs into difficulty doing something in Java, assistance is oft easy to find. Java ’ s seniority and popularity intend that countless developers have likely encountered the like trouble, leading to a plethora of online resources available for troubleshooting.
Combining the above with the fact that Selenium WebDriver itself iswell-documentedand has excellentcommunity support, development team may notice that it ’ s easy to start writing automated UI test scripts with Selenium and Java than they thought.
Getting Started with Selenium in Java
Now that we ’ ve cover the basics of what Selenium and Java are and how automated UI examination can benefit your organization, it ’ s time to dive into the tutorial portion of this article. Below, we will walk you through the following:
Setting up Java on your local machine
Installing and configuring the Eclipse IDE
Creating your Java project
Importing Selenium and JUnit dependance
Writing a simple UI examination script employ Java and Selenium WebDriver
1. Set up Java on your local machine
Our initiatory step in getting our local environment configure will be to install the Java Development Kit (or JDK). For our purposes, JDK 17 is appropriate and can be downloadhere.
Choose the appropriate option for the OS on which you are working, then download and install it. For Windows 10 user, the x64 Installer will suffice. After downloading, the installer allow you to set the location where the JDK will be establish. The default installation location in this example is C: \Program Files\Java\jdk-17\.

After completing the installation, verify it by opening a command prompt and running the undermentioned dictation:
java -version

2. Install and configure the Eclipse IDE
With Java instal, we will involve an IDE in which we ’ ll pen our code. The Eclipse IDE is a popular pick that will accommodate our design just fine. Eclipse can be downloadhere.
Choose Eclipse IDE for Java Developersand select the download that will work with your operating system. Proceed with the installation, installing to the directory of your choice.
After installing and opening Eclipse, we can insure that it uses the JDK we instal in the previous step. In the navbar at the top of Eclipse, clickWindowfollow byPreferences.
In the Preferencesmodal, expandJavaand selectInstalled JREs. From within theInstalled JREswindow, clinkAddand selectStandard VM.

Click Next and set JRE hometo the location of the freshly installed JDK. ClickFinishand check the box next to the JRE entry that you merely configured.

3. Create your Java project
Now, let ’ s make a very bare Maven project that we can use to import Selenium and JUnit dependencies and write our sample test script.
Exposed Eclipse to a clean workspace location. I ’ ll be using the following placement on my machine:
C: \development\workspace
To create your project in Eclipse, go toFile, then New, and then click Maven Project. Check the boxCreate a simple project (skip pilot selection)and leave Use default Workspace placementchecked. ClickNextto move.

On the next screen, entersamples as the Group Id and selenium-with-java as the Artifact Id. Then clickFinish.

With that, the project has been make and we can get to act. It should now demo in thePackage Explorerview within your Eclipse IDE.
4. Import the Selenium and JUnit dependencies
The next step is to convey in the dependance required to write our sample trial script. For the purposes of this demonstration, we ’ ll need the Selenium WebDriver language bindings for Java as good as the JUnit Jupiter API.
To pull in version 4.10.0 of the Selenium libraries for Java, add the following to the dependencies parcel of your POM file:
& lt; dependency & gt;
& lt; groupId & gt; org.seleniumhq.selenium & lt; /groupId & gt;
& lt; artifactId & gt; selenium-java & lt; /artifactId & gt;
& lt; adaptation & gt; 4.10.0 & lt; /version & gt;
& lt; /dependency & gt;
More info on this can be found in theSelenium WebDriver instalment documentation.
Similarly, to draw in edition 5.9.3 of the JUnit Jupiter API, add the following to the habituation share of your POM file:
& lt; habituation & gt;
SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.
& lt; groupId & gt; org.junit.jupiter & lt; /groupId & gt;
& lt; artifactId & gt; junit-jupiter-engine & lt; /artifactId & gt;
& lt; version & gt; 5.9.3 & lt; /version & gt;
& lt; /dependency & gt;
Right-click on your project, navigate toMaven, then Update Project, and select the sample project to update. ClickingOKshould ensure that the above dependencies are force in and can now be utilized within your code.
5. Write a simple UI Test script use Java and Selenium WebDriver
With our new Java projection created and our habituation pulled in, we can now continue with develop a test book.
For this example, we ’ ll navigate to the Sauce LabsRequest a Demo pagein Google Chrome and ensure that the first name field, last gens field, and company battlefield are present on the page.
The initiatory step is to create a Java class within our project. To do so in Eclipse, go toFile, then New, and selectClass. Enter the package in which you wish to make your stratum as well as the class name. Let ’ s store this class in a package called selenium and nominate the classSauceTest.
Click Finishto create the fileSauceTest.java.
The next step is to create oursetUp and tearDownmethods. We will annotate these with@ BeforeEach and @ AfterEach, severally, so that they run before and after each method annotate with@Test. The setUpmethod will be responsible for configuring our class variablewebDriver as a ChromeDriver, while tearDownwill be creditworthy for callingquit on webDriverand shut all associated Chrome windows. Here ’ s what those two methods will seem like:
@ BeforeEach
public void apparatus () {
System.out.println (& quot; * * * set up * * * & quot;);
System.setProperty (& quot; webdriver.chrome.driver & quot;, & quot; C: //development//chromedriver//chromedriver.exe & quot;);
webDriver = new ChromeDriver ();
}
@ AfterEach
public void tearDown () {
System.out.println (& quot; * * * tear down * * * & quot;);
webDriver.quit ();
}
Next, we ’ ll progress ourdemoFormTestmethod annotated with@Test. This method will use the Selenium dependance that we ’ ve draw into our project to accomplish the following:
Open a Chrome window
Navigate to
Check for the existence of the 1st name, last name, and fellowship fields
The trial will pass if all three fields are present. If any of the three fields are not present, the test will betray. Please see the entireSauceTestclass below:
software selenium;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
importee org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SauceTest {
private WebDriver webDriver;
@ BeforeEach
public void setUp () {
System.out.println (& quot; * * * set up * * * & quot;);
System.setProperty (& quot; webdriver.chrome.driver & quot;, & quot; C: //development//chromedriver//chromedriver.exe & quot;);
webDriver = new ChromeDriver ();
}
@Test
public void demoFormTest () {
System.out.println (& quot; * * * trial * * * & quot;);
webDriver.get (& quot;");
boolean expectedFieldsExist;
try {
webDriver.findElement (By.id (& quot; FirstName & quot;));
webDriver.findElement (By.id (& quot; LastName & quot;));
webDriver.findElement (By.id (& quot; Company & quot;));
expectedFieldsExist = true;
} catch (NoSuchElementException e) {
expectedFieldsExist = false;
}
assertTrue (expectedFieldsExist);
}
@ AfterEach
public void tearDown () {
System.out.println (& quot; * * * tear down * * * & quot;);
webDriver.quit ();
}
}
After executing the tryout, you can ensure the Console and JUnit sight in Eclipse for information consider the output. The icon below demonstrate what can be wait:


Wrapping Up
Both Java and Selenium are good documented and supported, and they provide great value to many software ontogenesis squad. As such, they are an excellent match when use in conjunction with one another.
Considering the often rapid step at which software is developed and modified, it ’ s important to test your code groundwork as it evolves. When done manually, this can be a time-consuming and error-prone process. When accomplished with the help of machine-driven testing tools such as Selenium, it is efficient and consistent.
Related resources
Share this post
Ready to start testing with Selenium and Sauce Labs?
Let & # x27; s go!
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free

