Practical 15: Creating JUnit Tests using Eclipse
Aim
Set up a Java test project in Eclipse with JUnit and Selenium. Test the website search with matching text, different letter case, no matching result and empty input. Read the JUnit results.
Theory
JUnit runs tests written in Java and reports whether they pass. Selenium WebDriver performs browser actions. The two tools have different jobs in this exercise.
WebDriver enters the search text and submits it. JUnit checks the result using assertions, which compare what happened with what you expected.
WebDriver is the student who actually does the actions in the browser (types the search word, clicks Search). JUnit is the examiner who sets up the exam hall (@Before), checks the answers (assertEquals), and announces the result in green (pass) or red (fail).
JUnit 4 annotations
| Annotation | Runs |
|---|---|
@BeforeClass |
Once before all tests in the class (static) – for example start the browser |
@Before |
Before each test – for example open the home page |
@Test |
Marks a test method; options expected=…, timeout=… |
@After |
After each test |
@AfterClass |
Once after all tests – for example quit the browser |
@Ignore |
Skip a test |
(JUnit 5 equivalents: @BeforeAll, @BeforeEach, @Test, @AfterEach, @AfterAll, @Disabled.)
Assertions (org.junit.Assert)
assertEquals(expected, actual), assertNotEquals, assertTrue(condition), assertFalse, assertNull, assertNotNull, assertSame, assertArrayEquals, assertThat(actual, matcher), fail(message).
Test outcome in JUnit
| Result | Meaning | JUnit view |
|---|---|---|
| Pass | All assertions true | Green tick |
| Failure | An assertion failed (AssertionError) |
Blue cross |
| Error | An unexpected exception (for example NoSuchElementException) |
Red cross |
| Ignored | @Ignore |
Grey |
Requirements
The .test addresses refer to the simulated practice app. Outside the simulator, use a running test app and its actual addresses and page elements.
- Eclipse IDE (Integrated Development Environment), JDK (Java Development Kit) 17.
- Selenium Java 4.x JARs (Java Archives) (or Maven dependency) and JUnit 4.13.2 (+ Hamcrest).
- Chrome browser (Selenium Manager downloads ChromeDriver automatically in Selenium 4.6+).
- Application under test: VLP Demo Store with a search box (
id=search) that lists matching products (.product-card) and shows “No products found” for unknown terms.
Procedure
Part A – Set up the project
- File → New → Java Project →
WebSearchTests(untick module-info) → Finish. - Build Path → Configure Build Path → Libraries → Classpath → Add Library… → JUnit → JUnit 4.
- Add External JARs… → add all JARs from the Selenium Java folder (
selenium-java-4.x.jarandlib/*.jar). Maven alternative:
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.21.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
- Create package
vlp.testsand classSearchTest(New → JUnit Test Case, ticksetUpBeforeClass,tearDownAfterClass,setUp).
Part B – Write the JUnit test
package vlp.tests;
import static org.junit.Assert.*;
import java.time.Duration;
import java.util.List;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SearchTest {
private static WebDriver driver;
private static WebDriverWait wait;
private static final String BASE_URL = "https://demo.virtuallp.test/";
@BeforeClass
public static void setUpBeforeClass() {
driver = new ChromeDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Before
public void setUp() {
driver.get(BASE_URL);
}
@Test
public void searchReturnsMatchingProducts() {
WebElement box = driver.findElement(By.id("search"));
box.clear();
box.sendKeys("laptop");
box.sendKeys(Keys.ENTER);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".product-card")));
List<WebElement> results = driver.findElements(By.cssSelector(".product-card .title"));
assertTrue("Expected at least one result", results.size() > 0);
for (WebElement r : results) {
assertTrue("Unexpected result: " + r.getText(), r.getText().toLowerCase().contains("laptop"));
}
assertEquals("Search results for “laptop”", driver.findElement(By.cssSelector("h1")).getText());
}
@Test
public void searchIsCaseInsensitive() {
driver.findElement(By.id("search")).sendKeys("LAPTOP" + Keys.ENTER);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".product-card")));
assertFalse(driver.findElements(By.cssSelector(".product-card")).isEmpty());
}
@Test
public void unknownTermShowsNoResults() {
driver.findElement(By.id("search")).sendKeys("xyz123" + Keys.ENTER);
WebElement msg = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".empty-state")));
assertEquals("No products found", msg.getText());
}
@Test
public void emptySearchKeepsUserOnHomePage() {
driver.findElement(By.id("search")).sendKeys(Keys.ENTER);
assertEquals(BASE_URL, driver.getCurrentUrl());
}
@AfterClass
public static void tearDownAfterClass() {
if (driver != null) driver.quit();
}
}
Part C – Run and analyse
- Right-click
SearchTest.java→ Run As → JUnit Test. - Chrome opens and runs each test. The JUnit view shows:
- Runs: 4/4 Errors: 0 Failures: 0 and a green bar,
- the time taken by each test.
- Introduce a defect – for example change the expected heading – and re-run: the bar turns red/blue, and the Failure Trace shows
org.junit.ComparisonFailure: expected:<…> but was:<…>with the line number. Double-click the trace line to jump to the code. - Use Rerun Failed Tests to run only the failures after fixing.
Virtual lab · Testing Tools · 30 min
JUnit tests for a web application’s search
Explore the VLP Demo Store, add Selenium and JUnit to an Eclipse project, run four search tests that drive Chrome, then break and fix an expectation using the failure trace.
Output
Example output for the settings in this lesson:
JUnit view
Runs: 4/4 Errors: 0 Failures: 0
✔ SearchTest (8.214 s)
✔ searchReturnsMatchingProducts (3.102 s)
✔ searchIsCaseInsensitive (1.744 s)
✔ unknownTermShowsNoResults (1.689 s)
✔ emptySearchKeepsUserOnHomePage (0.913 s)
Conclusion
Check that all four search cases run. For any failure, read the expected and actual results in Eclipse. Use the error details to find the failed check before changing the code.
Viva questions
- What is JUnit? Why is it combined with Selenium? Java's standard unit-testing framework; it gives Selenium tests structure, setup/teardown, assertions and reports.
- Explain the JUnit 4 lifecycle annotations and their execution order.
@BeforeClass(once) → for each test:@Before→@Test→@After→@AfterClass(once). - Differentiate a failure and an error in JUnit. Failure = an assertion was false; error = an unexpected exception (for example element not found).
- Why is
@BeforeClassmethod static? It runs once before any test object is created, so it cannot belong to an instance. - What is the role of
WebDriverWait? It waits until a condition is true (element visible/clickable) before continuing, avoiding timing failures. - How do you add JUnit to an Eclipse project? Build Path → Add Libraries → JUnit (or add the JUnit dependency in Maven).
- Give the JUnit 5 equivalents of JUnit 4 annotations.
@BeforeAll,@BeforeEach,@AfterEach,@AfterAll,@Disabled(for@Ignore);@Teststays.
Practise this topic
Hands-on virtual lab
Apply what you just read in a realistic, guided simulation. Free with a verified account.
Create a free account to track your progress and unlock virtual labs.