Integration of Selenium with JUnit

  

Integrating Selenium with JUnit

JUnit and Selenium are often used together for automated UI testing. JUnit acts as the test runner and assertion framework, while Selenium automates browser actions.


Prerequisites for integration of Selenium with JUnit

  • Java installed
  • Eclipse or IntelliJ IDE
  • Maven or Gradle for dependency management
  • JUnit (JUnit 4 or 5)
  • Selenium WebDriver


Step 1: Maven pom.xml Dependencies


<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>selenium-junit-demo</artifactId>
  <version>1.0</version>
  
  <dependencies>
    <!-- Selenium -->
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>4.20.0</version>
    </dependency>

    <!-- JUnit 5 -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.10.2</version>
    </dependency>
  </dependencies>
</project>




Step 2: Basic Selenium + JUnit Test

This code will open google page and verify the title contains 'Google'



import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class GoogleTest {

    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        // Make sure to have chromedriver in your system PATH
        driver = new ChromeDriver();
    }

    @Test
    public void testGoogleTitle() {
        driver.get("https://www.google.com");
        String title = driver.getTitle();
        assertTrue(title.contains("Google"), "Title should contain 'Google'");
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}




Explanation


PartDescription
@BeforeEachRuns before each test – initializes WebDriver
@TestYour actual test logic using Selenium
@AfterEachRuns after each test – closes the browser
assertTrueAsserts that the page title contains "Google"


Running the Tests

  • Right-click the class → Run As > JUnit Test in Eclipse/IntelliJ
  • Or via terminal (if using Maven):

mvn test


Best Practices

  • Use Page Object Model (POM) for maintainability

  • Use WebDriverManager to auto-manage browser drivers

  • Prefer JUnit 5 over JUnit 4 for new projects