JUnit 5 Test Lifecycle

By | December 5, 2019

JUnit 5 Test lifecycle mainly contains 4 primary annotations:

  1. @BeforeAll
  2. @AfterAll
  3. @BeforeEach
  4. @AfterEach 

 Apart from above 4 each test method must be marked with any one of the below annotations

  1. @Test
  2. @RepeatedTest
  3. @ParameterizedTest
  4. @TestFactory
  5. @TestTemplate.

Before and After cycle annotations

When we write JUnit test cases then in JUnit test life cycle usually we primarily need to have some methods to setup and tear down the environment or test data on which the tests run.

When we run JUnit test cases then for each test – a new instance of test is created. 

When we looked into @BeforeAll and @AfterAll annotations. It is very clear by their name itself it should be called only once in entire tests execution cycle so they must be declared static.

In other hand @BeforeEach and @AfterEach are invoked for each instance of test so they need not to be static.

NOTE: If you annotate multiple methods with same annotation (e.g. two methods with @BeforeAll or AfterEach ) then their execution order is undetermined.

Let’s try to understand JUnit 5 Test Lifecycle annotations using an example project

Project Structure

Utility Class for that we have to write JUnit Test:

 JUnit Test Class with Life Cycle

 pom.xml

Output of above project

 

You may also like:
Junit 5 Architecture
JUnit 5 Annotations

That’s all about JUnit 5 Test Lifecycle
If you have any feedback or suggestion please feel free to drop in blow comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *