JUnit 5 Tutorial
A complete guide to writing modern Java tests with JUnit 5.
This series covers JUnit 5 from the basics through advanced topics like parameterized tests, nested tests, and migrating from JUnit 4.
- 1
Getting Started with JUnit 5: Writing Your First Test
This guide walks you through writing a simple JUnit 5 test to ensure your code works as intended. You’ll learn how to set up tests, verify expected results, and run them using an IDE, Maven, or Gradle.
- 2
JUnit 5 Assertions: Verifying Test Results
This article covers how to use JUnit 5 assertions to validate test results, including values, booleans, nulls, arrays, objects, exceptions, and timeouts. It explains custom error messages and grouped assertions for clearer reporting. For advanced scenarios, it also introduces third-party libraries like Hamcrest, AssertJ, and Truth to make assertions more readable and expressive.
- 3
JUnit 5 Test Lifecycle: Before and After Annotations
This tutorial explores how to run code before and after tests in JUnit 5, both for individual tests and across the entire test class. It explains the differences between per-test and per-class test instances, handling nested tests, and how extensions wrap test execution. Learning these patterns helps manage shared resources and maintain predictable test behavior.
- 4
JUnit 5 Nested Tests: Grouping Related Tests Together
This tutorial demonstrates how to use JUnit 5 nested tests to structure tests hierarchically, making it easier to group related cases and navigate results. It covers simple examples with nested classes, multi-layered nesting for REST controllers, and tips to avoid pitfalls like excessive duplication. Using nested tests improves readability and helps maintain clean, organized test code.
- 5
A More Practical Guide to JUnit 5 Parameterized Tests
This tutorial explains how to create parameterized tests in JUnit 5, allowing the same test to run with different inputs. It covers single and multiple arguments, using external data sources like CSV files, and custom conversions or aggregations for complex types. Parameterized tests help reduce duplication and make test code more maintainable and readable.
- 6
Using Mockito With JUnit 5
This guide explains how to integrate Mockito with JUnit 5 for effective unit testing. It covers three approaches: manual mock creation, annotation-based initialization, and using the Mockito JUnit 5 extension for automatic mock injection. By following these methods, you can simplify test setup, improve readability, and validate mock usage efficiently.
- 7
Migrating From JUnit 4 to JUnit 5: A Definitive Guide
Migrating from JUnit 4 to JUnit 5 involves updating dependencies, annotations, and testing classes while running old and new tests together. Custom runners and rules need to be replaced with extensions, and parameterized tests require rework to fit the new model. This guide provides step-by-step instructions for a smooth, gradual migration.