JUnit 5 @BeforeAll annotation example

By | December 6, 2019

In this post, we will talk and learn about the JUnit 5 life cycle @BeforeAll annotation.

In JUnit 5 @BeforeAll annotation is used to signal that the annotated method should be executed before all tests in the current test Class.

It is a replacement for @BeforeClass annotation in JUnit 4.

@BeforeAll annotated method must be declared as a static method otherwise it will throw runtime error.

@BeforeAll Annotation Example

Let’s understand @BeforeAll Annotation using an example. Here I have MyUtils.java class with the add method. I will write a Junit test for this add method and we will see how we can make use of @BeforeAll Annotation in the same Unit class.

Utility Class for that we have to write JUnit Test:

JUnit Test Class with non static method(setUp()) annotated with  @BeforeAll. In this case, JUnit 5 will throw a runtime exception.

Now in the above test class, we make the setUp() method static then the test case will be executed successfully.

 The output of the above test class

 

You may also Like:

Junit 5 Architecture
JUnit 5 Annotations
JUnit 5 Maven Dependency
JUnit 5 Test Lifecycle

That’s all about JUnit 5 @BeforeAll annotation example
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

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