Below is the code and explanation of JUnit Test with Selenium WebDriver in Java.
What is JUnit?
JUnit is a popular testing framework in Java used to write and run repeatable test cases. When integrated with Selenium WebDriver, JUnit helps automate UI/browser tests with setup and teardown capabilities.
Key JUnit Annotations:
| Annotation | Purpose |
|---|---|
| @Before | Runs before each test method |
| @After | Runs after each test method |
| @BeforeClass | Runs once before all tests |
| @AfterClass | Runs once after all tests |
| @Test | Marks a test method |
| @Ignore | Ignores the test method |
Simple Selenium Test with JUnit
Maven Dependencies in pom.xml
If you're using Maven, include below dependencies
<dependencies> <!-- Selenium WebDriver --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.20.0</version> </dependency> <!-- JUnit 4 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>
Full Example Using JUnit + Selenium
import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class GoogleSearchTest { WebDriver driver; @Before public void setUp() { // Set the path to your chromedriver executable if needed System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); } @Test public void testGoogleSearch() { // Navigate to Google driver.get("https://www.google.com"); // Find the search box and enter text WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("JUnit Selenium"); // Submit the search form searchBox.submit(); // Wait for results and assert try { Thread.sleep(2000); // use WebDriverWait in real tests } catch (InterruptedException e) { e.printStackTrace(); } // Check title contains the search keyword String title = driver.getTitle(); assertTrue("Title should contain search term", title.contains("JUnit Selenium")); } @After public void tearDown() { if (driver != null) { driver.quit(); // Close the browser } } }
What This Code Does:
@Before: Sets up WebDriver before each test.@Test: Opens Google, performs a search, and verifies the result.@After: Quits the browser after each test.
To Run the Test:
If using IDE: Right-click > Run As > JUnit Test
If using Maven: Use mvn test (requires Surefire plugin)