Shmoe
Shmoe

Reputation: 51

How to initialize a static resource in the base class for all tests in the project using JUnit 5?

Given the following code:

    public abstract class Base {

      @BeforeAll
      public static void beforeAll() {
        System.out.println("Base::beforeAll");
      }

      @AfterAll
      public static void afterAll() {
        System.out.println("Base::afterAll");
      }
    }

    public class First extends Base {

      @Test
      public void test() {
        System.out.println("First::test");
      }
    }

    public class Second extends Base {

      @Test
      public void test() {
        System.out.println("Second::test");
      }
    }

I would like to have the following execution model:

    Base::beforeAll
    First::test
    Second::test
    Base::afterAll

Instead, I get this:

    Base::beforeAll
    First::test
    Base::afterAll

    Base::beforeAll
    Second::test
    Base::afterAll

I'm aware of BeforeAllCallback and AfterAllCallback, but they simply provide the callback hooks for lifecycle annotations like BeforeAll and AfterAll.

Is there any way you can safely run a setup method in the base class before running all tests in the project and then run some tear down method after running all the test methods in the entire project?

Upvotes: 4

Views: 2472

Answers (1)

Shmoe
Shmoe

Reputation: 51

Looks like you can use the combination of BeforeCallback and ExecutionContext in order to achieve this kind of behavior: https://stackoverflow.com/a/51556718/11692167

Upvotes: 1

Related Questions