🎯 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:

  • @Test and @DisplayName for readable test methods
  • @BeforeEach / @AfterEach for per-test setup and teardown
  • assertEquals, assertThrows, assertAll from JUnit 5's assertion API
  • @ParameterizedTest + @CsvSource to 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
💼 Interview reality: "What is the difference between @Before and @BeforeEach?" and "How would you write a parameterised test?" come up in virtually every senior Java backend interview. Understanding JUnit 5's lifecycle is foundational.

💼 Real-world scenario

💼
TaxSetu (Bangalore, India)
Test every tax slab before filing season

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.

mvn test -pl . -Dtest=TaxCalculatorTest
TaxCalculatorTest.javaLesson 31 · @Test, @BeforeEach, @DisplayName
verified output
[INFO] Running io.taxsetu.TaxCalculatorTest [INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.045 s -- in io.taxsetu.TaxCalculatorTest [INFO] BUILD SUCCESS

@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.

mvn test -Dtest="TaxCalculatorTest#newRegimeTaxTable"
TaxCalculatorTest.javaLesson 31 · @ParameterizedTest + @CsvSource
verified output — 4 parameterised variations
[INFO] Running io.taxsetu.TaxCalculatorTest [INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.033 s [INFO] BUILD SUCCESS

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.

mvn test
TaxCalculatorTest.javaLesson 31 · assertThrows + assertAll
verified output — full suite: 12 tests, 0 failures
[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.044 s -- in io.taxsetu.TaxCalculatorTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.370 s -- in io.taxsetu.TaxFilingServiceTest [INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS [INFO] Total time: 0.938 s

📋 JUnit 5 annotation reference

AnnotationWhen it runsNotes
@TestMarks a test methodNo runner annotation needed on the class
@DisplayNameN/A — metadataHuman-readable name in reports and IDEs
@BeforeEachBefore every test methodInstance method; used for per-test setup
@AfterEachAfter every test methodCleanup (close resources, reset state)
@BeforeAllOnce before all tests in the classMust be static (unless PER_CLASS lifecycle)
@AfterAllOnce after all tests in the classMust be static
@ParameterizedTestPer row of test dataRequires a provider: @CsvSource, @ValueSource, etc.
@DisabledNeverSkips the test; always add a reason string

🎤 Interview Q&A

EasyWhat is the difference between JUnit 4 and JUnit 5?
+

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+.

EasyDo test methods need to be public in JUnit 5?
+

No. JUnit 5 uses reflection and allows package-private (default) test methods. The convention is to omit public for cleaner test classes.

MediumHow do you run a single test class or method from Maven?
+

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".

MediumWhen should you use @BeforeAll vs @BeforeEach?
+

@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.

HardHow does JUnit 5's test lifecycle differ from JUnit 4, and what is @TestInstance(Lifecycle.PER_CLASS)?
+

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

Question 1 of 5
Which annotation marks a method as a JUnit 5 test?
Question 2 of 5
What does @BeforeEach do?
Question 3 of 5
How does assertThrows work?
Question 4 of 5
What is the benefit of @ParameterizedTest over multiple @Test methods?
Question 5 of 5
What does assertAll do differently from separate assertEquals calls?
0
/ 5
Quiz complete!

Next: Mockito and Mocking →

⚠️ Common mistakes

Forgetting @BeforeEach — tests share mutable state
If 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) in wrong order
Convention is assertEquals(expected, actual). Getting it backwards produces confusing failure messages: "expected 0 but was 10000" when you meant the opposite.
assertThrows without checking the exception message
assertThrows only checks the type. A bug might throw the right exception type with a wrong message. Always assert ex.getMessage() for complete coverage.
Not adding maven-surefire-plugin 3.x
JUnit 5 requires Surefire 2.22+ to run Jupiter tests. Older Surefire silently runs 0 tests. Always declare the plugin version explicitly in pom.xml.

✅ 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
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →