JUnit is a unit testing framework for the Java programming language. It plays a crucial role in test-driven development (TDD) and is used to write and run repeatable tests. JUnit belongs to the family of XUnit frameworks, and it is one of the most popular testing libraries in Java.
Key Features of JUnit
| Feature | Description |
|---|---|
| Annotations | Uses annotations like @Test, @BeforeEach, @AfterEach, @BeforeAll, @AfterAll, etc. |
| Assertions | Provides assertion methods like assertEquals(), assertTrue(), etc. |
| Test Runner | JUnit provides test runners to run test classes individually or as part of a suite. |
| Integration | Easily integrates with build tools like Maven/Gradle and IDEs like Eclipse, IntelliJ. |
Common JUnit 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 (must be static) |
| @AfterAll | Runs once after all test methods (must be static) |
| @Disabled | Skips a test method or class |
Simple Example of JUnit (JUnit 5)
Java Class to Test (
Calculator.java)public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
Test Class (
CalculatorTest.java)import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.*;
public class CalculatorTest {
Calculator calculator;
@BeforeEach
void setUp() {
calculator = new Calculator();
System.out.println("Before Each Test");
}
@AfterEach
void tearDown() {
System.out.println("After Each Test");
}
@Test
void testAddition() {
assertEquals(5, calculator.add(2, 3), "2 + 3 should equal 5");
}
@Test
void testSubtraction() {
assertEquals(1, calculator.subtract(3, 2), "3 - 2 should equal 1");
}
}
How to Run JUnit Tests
You can run JUnit tests in several ways:
From IDE like Eclipse/IntelliJ (Right-click → Run As → JUnit Test)
Using build tools like Maven/Gradle
Command line (using
javacandjavawith JUnit jars)
Maven Dependency for JUnit 5
If you're using Maven:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
Important Points:
- JUnit helps automate and structure your unit tests.
- It promotes cleaner code and faster debugging.
- Easily integrates with CI/CD tools, Maven, and IDEs.
- Essential for TDD and Agile methodologies.