JUnit 5 @BeforeAll annotation is replacement of @BeforeClass
annotation in JUnit 4. It is used to signal that the annotated method should be executed before all tests in the current test class.
@BeforeAll Annotation Usage
Annotate a method with @BeforeAll
as given below:
@BeforeAll public static void init(){ System.out.println("BeforeAll init() method called"); }
@BeforeAll
annotated method MUST be a static method otherwise it will throw runtime error.
org.junit.platform.commons.JUnitException: @BeforeAll method 'public void com.howtodoinjava.junit5.examples.JUnit5AnnotationsExample.init()' must be static. at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.assertStatic(LifecycleMethodUtils.java:66) at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.lambda$findBeforeAllMethods$0(LifecycleMethodUtils.java:42) at java.util.ArrayList.forEach(ArrayList.java:1249) at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080) at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.findBeforeAllMethods(LifecycleMethodUtils.java:42)
@BeforeAll Annotation Example
Let’s take an example. I have used one Calculator
class and added one add
method. I will test it 5 times using @RepeatedTest
annotation. This annotation will cause the add
test to run 5 times. But @BeforeAll
annotated method must be called only once.
package com.howtodoinjava.junit5.examples; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.RepetitionInfo; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) public class BeforeAllTest { @DisplayName("Add operation test") @RepeatedTest(5) void addNumber(TestInfo testInfo, RepetitionInfo repetitionInfo) { System.out.println("Running test -> " + repetitionInfo.getCurrentRepetition()); Assertions.assertEquals(2, Calculator.add(1, 1), "1 + 1 should equal 2"); } @BeforeAll public static void init(){ System.out.println("Before All init() method called"); } }
Where Calculator class is:
package com.howtodoinjava.junit5.examples; public class Calculator { public static int add(int a, int b) { return a + b; } }
Now execute the test and you will see below console output:
Before All init() method called Running test -> 1 Running test -> 2 Running test -> 3 Running test -> 4 Running test -> 5
Clearly, @BeforeAll
annotated init()
method is called only once.
Happy Learning !!
Divyansh
How add() method from Calculator class is accessible directly because it’s not static method?