Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

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.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!