🎯 What you will learn
JUnit 5 is the standard unit testing framework for Java. It introduced a cleaner annotation model, a powerful extension API, and built-in support for parameterised tests. By the end of this lesson you will understand:
@Testand@DisplayNamefor readable test methods@BeforeEach/@AfterEachfor per-test setup and teardownassertEquals,assertThrows,assertAllfrom JUnit 5's assertion API@ParameterizedTest+@CsvSourceto test multiple inputs with one method- Running tests with Maven Surefire 3.x and reading the output
- How JUnit 5 test lifecycle differs from JUnit 4
💼 Real-world scenario
TaxSetu's tax calculator must be bulletproof before millions of ITR filings start. Rohan writes JUnit 5 tests for every Indian income slab — NIL, 5%, 10%, 15%, 20% — using parameterised tests and @BeforeEach so each case is independent and reproducible.
🧪 @Test, @BeforeEach, @DisplayName
JUnit 5 test methods are annotated with @Test. @BeforeEach runs before every individual test method, creating a fresh object so tests can't pollute each other's state. @DisplayName provides a human-readable label shown in test reports.
@BeforeEach vs field initialiser: If you write TaxCalculator calc = new TaxCalculator() directly on the field, JUnit 5 (by default) creates a new class instance per test method anyway — so both patterns work. @BeforeEach makes the reset intent explicit and lets you inject dependencies or configure the object per test.
📊 @ParameterizedTest + @CsvSource
Instead of writing one @Test method per tax slab, @ParameterizedTest with @CsvSource feeds each row as a separate test run. One method body covers all cases — each row appears as an independent test in the report.
Other providers: @ValueSource for a single-argument list of strings or ints. @MethodSource for a static factory method that returns a Stream of Arguments. @EnumSource to test every enum constant. @CsvSource is the most readable for tabular data.
🔬 assertThrows + assertAll
assertThrows passes if and only if the supplied lambda throws the specified exception type — and returns the caught exception so you can inspect its message. assertAll groups multiple assertions and reports every failure, not just the first.
📋 JUnit 5 annotation reference
| Annotation | When it runs | Notes |
|---|---|---|
@Test | Marks a test method | No runner annotation needed on the class |
@DisplayName | N/A — metadata | Human-readable name in reports and IDEs |
@BeforeEach | Before every test method | Instance method; used for per-test setup |
@AfterEach | After every test method | Cleanup (close resources, reset state) |
@BeforeAll | Once before all tests in the class | Must be static (unless PER_CLASS lifecycle) |
@AfterAll | Once after all tests in the class | Must be static |
@ParameterizedTest | Per row of test data | Requires a provider: @CsvSource, @ValueSource, etc. |
@Disabled | Never | Skips the test; always add a reason string |
🎤 Interview Q&A
JUnit 5 = JUnit Platform (test engine SPI) + JUnit Jupiter (new API) + JUnit Vintage (backward compat with JUnit 4). Key changes: @RunWith → @ExtendWith, @Before/@After → @BeforeEach/@AfterEach, rules replaced by extensions. JUnit 5 requires Java 8+.
No. JUnit 5 uses reflection and allows package-private (default) test methods. The convention is to omit public for cleaner test classes.
mvn test -Dtest=TaxCalculatorTest runs the entire class. mvn test -Dtest="TaxCalculatorTest#nilSlabNewRegime" runs a single method. Use comma-separation for multiple: -Dtest="ClassA,ClassB".
@BeforeAll for expensive one-time setup (starting a server, loading a large file) — must be static. @BeforeEach for cheap per-test reset (new object, clear mock) — instance method. If test objects are immutable, @BeforeAll is fine; if mutable, @BeforeEach prevents test pollution.
JUnit 4 and 5 default to creating a new test class instance per test method (test isolation). @TestInstance(Lifecycle.PER_CLASS) creates one instance for the whole class. This allows @BeforeAll/@AfterAll to be non-static (useful in Kotlin or when sharing expensive state). Trade-off: test order matters more if you share mutable state.
📝 Quiz — 5 questions
Next: Mockito and Mocking →
⚠️ Common mistakes
calc is assigned in the class field initialiser, all tests share one instance. If one test mutates it, the next test sees the mutated state. Use @BeforeEach to reset.assertEquals(expected, actual). Getting it backwards produces confusing failure messages: "expected 0 but was 10000" when you meant the opposite.assertThrows only checks the type. A bug might throw the right exception type with a wrong message. Always assert ex.getMessage() for complete coverage.✅ Key takeaways
- @Test marks test methods; @BeforeEach resets state before every test
- assertEquals(expected, actual) — expected first, actual second
- assertThrows captures the exception for further assertion
- @ParameterizedTest + @CsvSource eliminates duplicate test methods
- assertAll reports every failure at once instead of stopping at the first
From unit tests to bulletproof Java services
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →