Java
JUnit basics
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.
Exercise 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.
Show example 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));
}
}
Test yourself
-
Which annotation marks a test method?
- @TestMethod
- @Run
- @Test
- @TestCase
Show answer
@Test — @Test marks a method as a test in JUnit 5.
-
Complete the test method
@Test
void testAdd() {
Calculator c = new Calculator();
int result = c.add(2, 3);
____(5, result);
}
Show answer
@Test
void testAdd() {
Calculator c = new Calculator();
int result = c.add(2, 3);
assertEquals(5, result);
}
-
Match the JUnit concepts
- @Test
- Marks a test method
- Jupiter
- Provides the new test API
- Platform
- Engine that runs tests
- Assertions
- Verification methods
Next lesson: Assertions