1. Overview
In this short tutorial, we're going to implement non-static methods with @BeforeAll and @AfterAll annotations available in Junit5.
2. @BeforeAll and @AfterAll in Non-Static Methods
While unit testing, we may occasionally want to use @BeforeAll and @AfterAll in non-static setup and tear-down methods — for instance, in a @Nested test class or as interface default methods.
Let's create a test class with the @BeforeAll and @AfterAll methods as non-static:
public class BeforeAndAfterAnnotationsUnitTest {
String input;
Long result;
@BeforeAll
public void setup() {
input = "77";
}
@AfterAll
public void teardown() {
input = null;
result = null;
}
@Test
public void whenConvertStringToLong_thenResultShouldBeLong() {
result = Long.valueOf(input);
Assertions.assertEquals(77l, result);
}_
}
If we run the above code, it will throw an exception:
org.junit.platform.commons.JUnitException: ...
Let's now see how we can avoid this situation.
3. The @TestInstance Annotation
We'll use the @TestInstance annotation to configure the lifecycle of a test. If we don't declare it on our test class, the lifecycle mode will be PER_METHOD by default. So, to prevent our test class from throwing a JUnitException, we need to annotate it with @TestInstance(TestInstance.Lifecycle.PER_CLASS).
Let's redo our test class and add the @TestInstance(TestInstance.Lifecycle.PER_CLASS):
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class BeforeAndAfterAnnotationsUnitTest {
String input;
Long result;
@BeforeAll
public void setup() {
input = "77";
}
@AfterAll
public void teardown() {
input = null;
result = null;
}
@Test
public void whenConvertStringToLong_thenResultShouldBeLong() {
result = Long.valueOf(input);
Assertions.assertEquals(77l, result);
}
}
In this case, our test runs successfully.
4. Conclusion
In this short article, we've learned how to use @BeforeAll and @AfterAll in non-static methods. First, we started with a simple non-static example to show what happens if we don't include the @TestInstance annotation. Then, we annotated our test with @TestInstance(TestInstance.Lifecycle.PER_CLASS) to prevent throwing a JUnitException.
As always, the implementation of all these examples is over on GitHub.
The post @BeforeAll and @AfterAll in Non-Static Methods first appeared on Baeldung.
Image may be NSFW.Clik here to view.
Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.

Clik here to view.
