JUnit basics
- Java course
- Advanced
- Lesson 43/82
- 5 min
Learn to write tests with @Test.
JUnit basics
JUnit is a modern testing framework for Java. The current version, JUnit 5, is named Jupiter and lives in the org.junit.jupiter.api package. You mark a test method with the @Test annotation.
import org.junit.jupiter.api.Test;
class CalculatorTest {
@Test
void testAdd() {
// verify
}
}This annotation tells the framework that the method is a test; it runs it automatically. A test class can be any class, but the name usually follows the XxxTest pattern. This structure keeps code quality under control.
JUnit 5 architecture
JUnit 5 has three sub-modules: Platform is the engine that runs tests, Jupiter provides the new test API, and Vintage supports old JUnit 4 tests.
Platform integrates with IDEs and build tools (Maven, Gradle). Jupiter provides APIs like @Test, Assertions and @BeforeEach. Vintage lets old tests keep running during migration. New code uses only Jupiter.
Practice Write a Calculator class and its test
Define a Calculator class with an add(int a, int b) method that sums two numbers. In a CalculatorTest class, write a @Test method testAdd that verifies with assertEquals(5, c.add(2, 3)). Add a main method that prints add(2, 3) with System.out.println.
Starter code
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
// Define the Calculator class (add method returns the sum)
// Mark testAdd with the test annotation and call assertEquals
// Add a main method that prints add(2, 3)Sample solution
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Calculator {
int add(int a, int b) {
return a + b;
}
}
class CalculatorTest {
@Test
void testAdd() {
Calculator c = new Calculator();
assertEquals(5, c.add(2, 3));
}
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3));
}
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which annotation marks a test method?
- @TestMethod
- @Run
- @Test Correct answer
- @TestCase
Explanation: @Test marks a method as a test in JUnit 5.
2 Complete the test method
@Test
void testAdd() {
Calculator c = new Calculator();
int result = c.add(2, 3);
____(5, result);
}
@Test
void testAdd() {
Calculator c = new Calculator();
int result = c.add(2, 3);
assertEquals(5, result);
}
Explanation: assertEquals compares expected and actual values.
3 Match the JUnit concepts
| Term | Meaning |
|---|---|
@Test |
Marks a test method |
Jupiter |
Provides the new test API |
Platform |
Engine that runs tests |
Assertions |
Verification methods |