Unit testing with JUnit 5
Write clear, fast unit tests.
By Invicly Tech, , in Backend Java Development. About 10 minutes to read.
In short
JUnit 5 is the standard Java testing framework. You write small methods annotated with @Test that arrange data, call the code and assert the result.
Explained simply
A unit test is a small program that checks one piece of your code. It sets up some data, calls a method and checks that the result is what you expected. If it is not, the test fails and tells you exactly what went wrong.
JUnit is the standard tool for this in Java. You write a test class, mark methods with @Test, and use assertions such as assertEquals(5, calc.add(2, 3)). Your IDE, Maven and Gradle can all run every test with one click or command.
Good tests are fast and independent. A whole suite of hundreds of unit tests should run in seconds, and each test must pass or fail on its own, no matter which tests ran before it. Then you can run them after every change.
Tests are also documentation. A test named rejectsPasswordsShorterThanEightCharacters tells the next developer what the code is supposed to do. When they change something by mistake, a red test warns them before users do.
Press Play on a diagram to walk through it one step at a time.
- 1@BeforeAll
Runs once before all tests in the class
- 2@BeforeEach
Fresh setup before every single test
- 3@Test runs
Arrange, act, assert
- 4@AfterEach
Clean up after every test
- 5@AfterAll
Runs once after all tests finish
- 1Red
Write a small test for new behaviour; it fails
- 2Green
Write the simplest code that makes it pass
- 3Refactor
Clean up code and tests while staying green
- 4Repeat
Next small behaviour
- Back to step 1
In depth
How JUnit 5 is built
JUnit 5 has three parts. The JUnit Platform is the foundation that IDEs and build tools talk to; it discovers and launches tests. JUnit Jupiter is the programming model you write against: @Test, assertions, extensions. JUnit Vintage is an optional engine that runs old JUnit 3 and 4 tests on the same platform, which helps during migration.
The single dependency org.junit.jupiter:junit-jupiter brings the API, parameterized tests and the engine. Maven's Surefire plugin finds test classes whose names match Test*, *Test, *Tests or *TestCase; a class called CalculatorCheck is silently ignored. Gradle needs tasks.test { useJUnitPlatform() }. Spring Boot's spring-boot-starter-test already includes JUnit Jupiter, AssertJ and Mockito.
- 1IDE, Maven Surefire, Gradle
Ask the platform to run tests
- 2JUnit Platform
Discovers tests and reports results
- 3Test engines
Jupiter for JUnit 5 tests, Vintage for old ones
- 4Your test classes
@Test methods with assertions
Assertions that give good failure messages
assertEquals takes the expected value first and the actual value second; swapping them gives confusing messages like expected 7 but was 5 when the opposite is true. For doubles, pass a tolerance: assertEquals(0.3, result, 1e-9). assertThrows(IllegalArgumentException.class, () -> parse("x")) returns the exception, so you can also check its message.
assertAll runs several checks and reports every failure together instead of stopping at the first, which is useful for checking several fields of one result. Every assertion accepts an optional last argument with a message. Many teams prefer AssertJ, which reads like a sentence: assertThat(list).hasSize(3).contains("a"). It produces very clear failure output and is already included in Spring Boot's test starter.
- assertEquals(expected, actual)
- assertTrue(cond, "message")
- assertThrows returns the exception
- assertAll(() -> ..., () -> ...)
- assertTimeout(Duration.ofSeconds(1), () -> ...)
Parameterized tests and their sources
A @ParameterizedTest runs once per set of arguments, and each run appears as its own result. @ValueSource gives single values: ints, strings and so on. @CsvSource gives rows of several values, and you can use a text block for readability. @EnumSource runs for each constant of an enum. @NullAndEmptySource adds null and an empty string, which are classic edge cases. @MethodSource points to a static method that returns a Stream of Arguments, for objects that cannot be written as text.
Give runs readable names with name = "{index}: {0} + {1} = {2}". Parameterized tests are ideal for boundary values: if a discount starts at 100, test 99, 100 and 101 rather than random numbers.
- @ValueSource(strings = {"", " "})
- @CsvSource({"2, 3, 5", "-1, 1, 0"})
- @MethodSource("cases") with static Stream<Arguments> cases()
Naming and organising tests
A good test name says what behaviour is expected, in which situation. Patterns like withdraw_failsWhenBalanceTooLow or plain sentences with @DisplayName("fails when the balance is too low") both work; pick one and stay consistent. Inside each test, keep three visible parts: arrange (build inputs), act (call the method once), assert (check the result). Test one behaviour per test so a failure points at one cause.
@Nested inner classes group tests by situation, such as WhenEmpty and WhenFull, and the report shows them as a tree. @Tag("slow") lets you include or exclude groups in the build. @Disabled("reason") skips a test but should be temporary. Tests should not depend on run order; JUnit uses a fixed but deliberately non-obvious order.
- @Nested WhenEmpty
- totalIsZero
- checkoutIsRejected
- @Nested WithOneItem
- totalEqualsItemPrice
- removingItemEmptiesCart
- @Nested WithDiscountCode
- appliesTenPercent
- rejectsExpiredCode
Lifecycle, temp folders and extensions
By default JUnit creates a new instance of the test class for every test method. That is why fields set in one test never leak into the next, and why @BeforeAll methods must be static. If you annotate the class with @TestInstance(Lifecycle.PER_CLASS), one instance is shared and @BeforeAll can be non-static; then you must reset state yourself.
JUnit has useful built-in helpers. A parameter or field annotated with @TempDir gets a fresh temporary directory that is deleted afterwards, perfect for file code. TestInfo gives the current test's name. Extensions plug in extra behaviour through @ExtendWith: MockitoExtension creates mocks, and Spring's SpringExtension starts an application context. Most framework test support you will use is built as a JUnit extension.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Write tests with @Test and assertions~1h
- 2Use lifecycle annotations~1h
- 3Write parameterized tests~1h
- 4Name and structure tests clearly~1h
Key points
- Each test gets a new instance of the test class by default, so tests stay independent.
- Structure each test as arrange, act, assert, and test one behaviour per method.
- Use @ParameterizedTest to run the same check over many inputs.
- Use assertThrows to check that bad input raises the right exception.
Key terms
Tap a card to flip it. 0/5 known
Examples
class CalculatorTest {
private Calculator calc;
@BeforeEach
void setUp() { calc = new Calculator(); }
@Test
void addsTwoNumbers() {
assertEquals(5, calc.add(2, 3));
}
@ParameterizedTest
@CsvSource({"1,1,2", "2,3,5", "-1,1,0"})
void addsMany(int a, int b, int expected) { assertEquals(expected, calc.add(a, b)); }
}Testing rules and error messages of a validator
A PasswordPolicy rejects passwords that are too short or have no digit. Step 1: a happy-path test proves a good password passes. Step 2: assertThrows checks the exception type and returns it, so step 3 can assert the message users will see. Step 4: assertAll checks two independent rules and reports both if both fail. Each test name states the rule it protects.
class PasswordPolicyTest {
private final PasswordPolicy policy = new PasswordPolicy(8);
@Test
void acceptsLongPasswordWithDigit() {
assertDoesNotThrow(() -> policy.check("s3cretPass"));
}
@Test
void rejectsShortPasswordWithClearMessage() {
var ex = assertThrows(IllegalArgumentException.class, () -> policy.check("ab1"));
assertEquals("password must have at least 8 characters", ex.getMessage());
}
}Boundary values with @MethodSource
Shipping is free from an order total of 50.00. Bugs hide at the edges, so step 1: list cases just below, exactly at and above the boundary, plus zero. Step 2: return them from a static method as a Stream of Arguments. Step 3: the parameterized test runs once per row with a readable name. If someone changes >= to >, the 50.00 row fails immediately.
static Stream<Arguments> totals() {
return Stream.of(
Arguments.of(new BigDecimal("0.00"), false),
Arguments.of(new BigDecimal("49.99"), false),
Arguments.of(new BigDecimal("50.00"), true),
Arguments.of(new BigDecimal("50.01"), true));
}
@ParameterizedTest(name = "total {0} -> free shipping: {1}")
@MethodSource("totals")
void freeShippingFromFifty(BigDecimal total, boolean expected) {
assertEquals(expected, Shipping.isFree(total));
}Quick reference
- assertEquals(expected, actual): expected always comes first
- assertThrows returns the exception so you can check its message
- assertAll reports every failing check, not just the first
- ./mvnw test -Dtest=CartTest#addsItem runs a single test method
- ./gradlew test --tests 'CartTest.addsItem' runs one test in Gradle
- Surefire only picks up classes named *Test, Test*, *Tests or *TestCase
- @TempDir Path dir gives a fresh folder that is deleted afterwards
- A new test class instance is created for every test method by default
Common mistakes
- Tests that depend on the order they run in.
- Asserting too many unrelated things in one test.
- Names like test1 that do not say what behaviour is checked.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write tests for a method boolean isLeapYear(int year). Cover 2024, 2023, 1900 and 2000.
- Exercise 2medium
Write one parameterized test for String slugify(String title), for example "Hello World" to "hello-world" and " Java 21! " to "java-21".
- Exercise 3hard
Test a class NotesStore that saves notes to files in a given folder: saving then loading returns the same text, and loading a missing note throws NoSuchFileException.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What changed from JUnit 4 to JUnit 5?
- Annotations moved to org.junit.jupiter.api, @Before and @After became @BeforeEach and @AfterEach, rules were replaced by extensions, and test classes and methods no longer need to be public. JUnit 6, released in 2025, keeps the same Jupiter API and requires Java 17.
- Should I use JUnit assertions or AssertJ?
- Both work. AssertJ's fluent assertThat style gives richer checks for collections, strings and exceptions and clearer messages, and it is included in the Spring Boot test starter.
- How do I measure test coverage?
- Add the JaCoCo plugin to Maven or Gradle; it produces an HTML report of which lines and branches your tests ran. Use it to find untested logic, not as a number to chase.
- How many unit tests should one method have?
- One per behaviour: the normal case, each edge case, and each error case. A parameterized test can cover many input values for the same behaviour.