JUnit 5 and Java 21: Modern Testing Practices

πŸ“Œ Introduction

Testing your code is just as important as writing it. With JUnit 5 and the new features of Java 21, testing has become more powerful, readable, and flexible. This post will help you learn how to set up and write clean, modern tests using JUnit 5 and Java 21 β€” in the simplest way possible.

JUnit 5 and Java 21: Modern Testing Practices

πŸš€ Why JUnit 5?

JUnit 5 is the latest version of the most widely used testing framework in Java. It’s better than the old JUnit 4 because:

  • It uses annotations that are more readable.
  • It’s built with modularity, making it easier to extend.
  • It supports Java 8+ features like lambdas, streams, and now Java 21 features.

🧰 Prerequisites

To follow along, make sure you have:

  • Java 21 installed
  • Maven or Gradle for dependency management
  • An IDE like VS Code or IntelliJ IDEA

βš™οΈ Maven Setup

Add these dependencies to your pom.xml:

πŸ§ͺ Writing Your First Test with JUnit 5

Let’s test a simple method:

Now let’s write a test:

πŸ“ What’s Happening?

  • @Test tells JUnit to run this method as a test.
  • assertEquals(expected, actual) checks if the result matches what we expect.

πŸ†š JUnit 4 vs JUnit 5

FeatureJUnit 4JUnit 5
Annotation@Test@Test (same)
Parameterized TestsExternal LibsBuilt-in
Dynamic Tests❌ Not availableβœ… Supported
Java 21 Features Support❌ Limitedβœ… Excellent

🧠 Java 21 + JUnit 5: Using record in Tests

Java 21 supports records, which are useful for test data:

πŸ§ͺ Advanced JUnit 5 Features

1. Parameterized Tests

Run a test with multiple inputs:

2. Test Lifecycle with Annotations

πŸ”„ Modern Practices

PracticeWhy it’s Good
Use record for test dataClean and immutable
Name your tests clearlyEasy to understand
Use @DisplayNameMakes reports readable
Keep test methods shortBetter maintenance
Test only one thing per testEasy to debug

πŸ§ͺ Structured Concurrency (Java 21) in Testing

You can now write tests for concurrency using structured concurrency:

This test checks two parallel tasks using Java 21’s structured concurrency.

βœ… Conclusion

With JUnit 5 and Java 21, testing is cleaner, faster, and more powerful. Even if you’re a beginner, you can write professional-grade tests that help catch bugs early and improve code quality.

So go ahead β€” write tests and refactor with confidence!

Reference : JUnit 5 User Guide