Here's a step-by-step guide to writing your first JUnit test in Eclipse, using JUnit 5 (also known as JUnit Jupiter).
Step 1: Set Up Eclipse Project
- Open Eclipse.
- Go to
File→New→Java Project. - Name the project, example:
JUnitDemo. - Click
Finish.
Step 2: Add JUnit 5 Library
- Right-click the project →
Build Path→Add Libraries. - Select JUnit → Click Next.
- Choose JUnit 5 → Click Finish.
If JUnit 5 is not available, you may need to download JUnit 5 from Maven/Gradle or manually add its
.jar files.Step 3: Create a Class to Test
Create a Java class that has some logic you want to test.
// File: Calculator.java public class Calculator { public int add(int a, int b) { return a + b; } }
Step 4: Create a JUnit Test Class
- Right-click on the
srcfolder →New→JUnit Test Case. - Name it
CalculatorTest. - Select JUnit 5 as the version.
- Click Finish.
Step 5: Write Your First Test
// File: CalculatorTest.java import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { @Test public void testAddition() { Calculator calc = new Calculator(); int result = calc.add(10, 5); assertEquals(15, result, "10 + 5 should equal 15"); } }
Step 6: Run the Test
- Right-click on
CalculatorTest.java.
- Select
Run As→JUnit Test.
JUnit 5 Key Annotations
| Annotation | Description |
|---|---|
| @Test | Marks a method as a test method |
| @BeforeEach | Runs before each test method |
| @AfterEach | Runs after each test method |
| @BeforeAll | Runs once before all test methods (static) |
| @AfterAll | Runs once after all test methods (static) |
| @Disabled | Disables a test temporarily |