Effective JUnit Testing Techniques for Selenium

JUnit Testing Techniques for Selenium

JUnit is a lightweight and beginner-friendly testing framework that facilitates the preparation, execution, and verification of tests quickly and reliably.

When combined with Selenium, JUnit offers tools to start and manage Selenium WebDriver. WebDriver is an interface that interacts with a web browser in a simple way, such as clicking buttons or entering text into fields.

Using JUnit, you can handle user sessions and assert expectations and conditions, enabling the execution of comprehensive UI tests with Selenium. This article will guide you through a step-by-step process for running JUnit testing for Selenium.

What Is JUnit?

JUnit is a Java testing framework that helps developers create reliable and efficient tests. It is mainly used for testing Java applications and supports automated testing. While it can be used with other languages, it works best for Java-based projects.

JUnit has many useful features that make writing tests easier. It supports different types of test cases, provides strong validation methods, and generates detailed test reports. Because of its flexibility, JUnit is widely used in software development.

JUnit is part of the xunit family of testing frameworks, which were inspired by earlier testing tools like those used in C++. It is designed to handle various types of tests, including unit tests, functional tests, and integration tests.

Unit tests check individual parts of an application to ensure they work correctly. Functional tests examine how the entire system performs as a whole. Integration tests focus on how various parts of the system work together.

JUnit is popular because it is flexible, feature-rich, and easy to use. It plays an important role in making Java applications more reliable by supporting different types of testing.

How Does JUnit Work?

JUnit is a testing framework that helps developers verify their applications. It lets developers write tests in Java and execute them on the Java platform. JUnit also includes a built-in reporter that prints the results of the tests.

There are two main objectives of automation testing with JUnit. The first objective is to confirm that the software performs as expected. If a piece of code is designed to function in a certain way but does not, it is important to detect the issue early so it can be corrected. The second objective is to identify errors in the code. Fixing bugs before they cause bigger problems helps maintain software stability.

JUnit provides different types of tests. Unit tests check individual pieces of code within a class or method. Integration tests examine how different parts of the application interact. System tests evaluate entire systems such as web servers. Running multiple tests together saves time when multiple tests need to be executed. Otherwise, testing can take a long time to complete. JUnit can be used from the command line or within Eclipse.

JUnit includes several features that make it easier to create and execute tests:

  • Assertions: Assertions help verify the expected behavior of a system. JUnit provides various assertion methods to check test results.
  • Test Runners: Test runners execute tests and display results. JUnit includes a graphical test runner for running tests and viewing outcomes.
  • Test Suites: Test suites group related tests together. JUnit provides a way to organize test suites and run them as a set.
  • Reporting: JUnit generates reports that display test execution details, making it easier to analyze results.

JUnit helps developers automate testing, detect errors early, and improve software quality with structured test execution.

What are the Features of JUnit?

  • Unit Testing Framework: JUnit is an open-source unit testing framework for Java that helps developers write and execute unit tests for program logic.
  • Assertions: JUnit provides annotations that help create tests. It includes assertion methods to verify whether the program logic works as expected.
  • Visual Feedback: JUnit displays test results using two checkmarks. A red checkmark indicates a failed test, while a green checkmark shows a passed test.
  • Annotations: JUnit uses annotations to define test methods and control execution. Some common annotations include @Test, @Before, and @After.
  • Test Suite: JUnit allows multiple test cases to be grouped into a test suite. @RunWith(Suite.class) and @Suite.SuiteClasses help execute multiple test classes together.

What are the Features of Selenium?

  • Automation Tool: Selenium is used for UI testing. It mimics user actions to check if the interface functions correctly. If any issue occurs, it throws an error to help identify the problem.
  • Simple Commands: Selenium provides simple commands and a wide range of functions that help manipulate the DOM for testing purposes.
  • Functional Testing: Selenium allows testers to perform actions like submitting forms, clicking buttons, and searching for content in a browser.
  • Cross-Browser Testing: Selenium supports cross-browser testing, meaning a script written for one browser can be executed on others without modification.
  • Selenium WebDriver: Selenium WebDriver is the most widely used feature. It provides APIs that allow testers to interact with browsers by calling functions directly.

How to Create and Execute JUnit Tests for Selenium

Prerequisites for Creating a Test with JUnit

To create a test using the JUnit framework, the following requirements must be met:

  • Maven as a Build Tool: Maven is a project management tool used for building projects and managing documentation and resources. It helps compile Java code, download libraries like JUnit and Selenium, and run tests.
  • Java Version 1.8 or Above: JUnit requires Java 1.8 or later. The latest version can be downloaded from the official website.
  • Integrated Development Environment (IDE: Code development will be done using IntelliJ IDEA. However, any other IDE can be used based on preference. Code snippets can be migrated to different platforms as needed.

Creating a Project in IntelliJ IDEA

To create a new project in IntelliJ IDEA, follow these steps:

  1. Click on FileNewProject.
  2. Select Maven as the project type.
  3. Click Next and proceed to the next step.

Setting Up Project Details

  • Specify a Group ID (a folder structure for the project).
  • Enter an Artifact ID (the project name).
  • Set the Version of the project.

Project Structure

Once the project is created, the structure includes:

  • src/test/java/environment – Contains two classes:
    • EnvironmentManager – Initializes and shuts down WebDriver.
    • RunEnvironment – Maintains the WebDriver instance and controls access to it.
  • test/java/tests – Includes a class DemoTest, which contains a test method to verify the homepage of com.
  • xml – The project’s configuration file, where dependencies are declared.

Adding Selenium and JUnit Dependencies

The pom.xml file includes the Selenium dependency:

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.9.0</version>
</dependency>

JUnit dependency must also be added. JUnit has two major versions: JUnit 3/4 (which are similar) and JUnit 5. The way dependencies are loaded and tests are executed depends on the version. This will be discussed later in the blog.

Next, we will look at how to initialize and shut down WebDriver.

Initializing Selenium

To run a test in the Chrome browser, the ChromeDriver executable must be downloaded from the official website.

Setting Up ChromeDriver

Once downloaded, the absolute path of ChromeDriver must be added to the PATH environment variable. This can be done programmatically or through OS tools. Below is the code snippet from test/java/environment/EnvironmentManager that sets it up programmatically:

public static void initWebDriver() {
System.setProperty(“webdriver.chrome.driver”, “C:/chromedriver.exe”);
WebDriver driver = new ChromeDriver();
RunEnvironment.setWebDriver(driver);
}

Note: The path to chromedriver will be different for Unix-based operating systems.

Shutting Down WebDriver

To close the WebDriver instance after the test runs, use the following method:

public static void shutDownDriver() {
RunEnvironment.getWebDriver().quit();
}

Creating a JUnit Test

Once the WebDriver setup is complete, the next step is to create a JUnit test.

import environment.EnvironmentManager;
import environment.RunEnvironment;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import static org.junit.Assert.assertEquals;public class DemoTest {

@Before
public void startBrowser() {
EnvironmentManager.initWebDriver();
}

@Test
public void demo() {
WebDriver driver = RunEnvironment.getWebDriver();
driver.get(“https://www.lambdatest.com/”);
String homeUrl = driver.findElement(By.cssSelector(“div#logo > a”)).getAttribute(“href”);
assertEquals(homeUrl, “https://www.lambdatest.com/”);
}

@After
public void tearDown() {
EnvironmentManager.shutDownDriver();
}
}

Understanding JUnit Annotations

  • @Test – Marks the method as a test case.
  • @Before – Runs before each test to initialize the WebDriver.
  • @After – Runs after each test to close the WebDriver.

If the homepage link does not match https://www.lambdatest.com/, the test will fail and throw an AssertionError.

Executing Tests in JUnit

To run tests correctly, dependencies must be defined in pom.xml, and the execution process differs for JUnit 4 and JUnit 5.

JUnit 4 Execution

Declare the following dependency in pom.xml under the <dependencies> tag:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

Running Tests

  • To run a single test, use the command:
mvn -Dtest=DemoTest test

To run all tests in a batch, execute:

mvn test

Test classes should be prefixed with *Test to be executed by Maven.

Test execution results will be displayed in the console:

——————————————————-
TESTS
——————————————————-
Running tests.DemoTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 13.167 sec
Results: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

JUnit does not have built-in reporting. To generate an HTML report, add the following maven-surefire-report-plugin to pom.xml:

<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.20.1</version>
</plugin>
</plugins>
</reporting>

The report will be generated in the surefire-reports directory. To convert this into an HTML report, run:

mvn surefire-report:report

The output will be available in the site directory.

JUnit 5 Execution

Instead of JUnit 4, declare the following dependency in pom.xml:

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.0.1</version>
<scope>test</scope>
</dependency>

JUnit 5 requires the junit-jupiter-engine dependency in maven-surefire-plugin:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.1</version>
</dependency>
</dependencies>
</plugin>

JUnit 5 uses different imports and annotations:

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;public class DemoTest {

@BeforeEach  // Changed from @Before
public void startBrowser() {
EnvironmentManager.initWebDriver();
}

@Test
public void demo() {
WebDriver driver = RunEnvironment.getWebDriver();
driver.get(“https://www.lambdatest.com/”);
String homeUrl = driver.findElement(By.cssSelector(“div#logo > a”)).getAttribute(“href”);
assertEquals(homeUrl, “https://www.lambdatest.com/”);
}

@AfterEach  // Changed from @After
public void tearDown() {
EnvironmentManager.shutDownDriver();
}
}

JUnit 5 requires an additional dependency for reporting:

<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.0.1</version>
</dependency>

 

Final maven-surefire-plugin configuration:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
</plugin>

 

By following these steps, tests can be created and executed using JUnit with Selenium and Maven. JUnit provides flexibility to run parameterized tests and dynamic tests, as well as make assumptions based on conditions.

Executing JUnit test cases using cloud testing platforms like LambdaTest provides access to a wide range of real browsers and operating systems. Running tests in the cloud helps teams detect issues early and maintain software quality across different configurations.

LambdaTest is an AI-native test orchestration and execution platform. It helps you perform automation testing with JUnit on a remote test lab of 5000+ real desktop browsers, devices, and operating system combinations.

By combining JUnit, Selenium, and LambdaTest, teams can simplify their testing process. Automating test execution ensures that applications function correctly across different platforms. This approach reduces manual effort and helps deliver high-quality software with fewer defects.

Conclusion

JUnit provides a structured approach to automated testing with Selenium. It helps teams execute test cases and verify web application functionality across different environments. Running JUnit tests in a cloud-based environment expands test coverage and reduces infrastructure requirements. It enhances test execution speed by reducing the need for local infrastructure. Cloud-based testing provides access to multiple environments and helps teams identify compatibility issues across different platforms.

By Jude

Elara writes from the quiet edges of the digital world, where thoughts linger and questions echo. Little is known, less is revealed — but every word leaves a trace.