A pattern for structuring JUnit tests using @Nested classes and @RegisterExtension to create declarative scenario trees with scoped fixture lifecycle management. Each nested class represents a 'Given' clause, and fixtures set up once per scope using ExtensionContext.Store.computeIfAbsent with 'this' as the key. This ensures expensive setup (servers, users, databases) runs only once per scope, tears down automatically, and any subtree can run in isolation. The post covers the core mechanism, fixture-as-factory pattern, Java 16+ compatibility requirement, JUnit 5 vs 6 API differences, and honest trade-offs including learning curve and parallel execution concerns.

12m read timeFrom codecentric.de
Post cover image
Table of contents
The Typical ProblemThe patternThe piece that makes it work: Store + computeIfAbsentFixtures as factoriesCompatibilityWhen to useWhen not to useSummary

Sort: