JUnit Test Lifecycle Annotations
Learn about the annotations used at different stages of the test lifecycle.
We'll cover the following
JUnit provides us with some lifecycle hooks that can be plugged in at various places in the test cycle. For example, some initialization code needs to be run before each test, and some cleanup code needs to be run after each test. If we have multiple tests, there might be some code that we want to initialize before any of the tests run. Similarly, there might be some teardown code that we want to run after each test has run.
JUnit provides annotations that can be used on each of these lifecycle hooks. These annotations are @BeforeAll
, @AfterAll
, @BeforeEach
, and @AfterEach
. The following image shows how these annotations are used at different stages in the lifecycle of a test.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.