Search⌘ K
AI Features

Test Instance Lifecycle

Understand how JUnit 5 manages test instance lifecycles to ensure test independence and control mutable state. Learn the difference between per-method and per-class lifecycles and how to use annotations like @BeforeAll and @AfterAll with non-static methods. Explore techniques to reset state in tests and apply lifecycle strategies to improve your unit testing.

We'll cover the following...

Per-class test instance lifecycle

By default, JUnit creates a new instance of each test class before executing each test method. That’s why the @BeforeAll and @AfterAll annotations can only be added to static methods by default. This per-method test instance Lifecycle is appropriate for most cases because test methods in a test class should be independent and verify different aspects of the same target ...