79692838

Date: 2025-07-07 12:25:55
Score: 0.5
Natty:
Report link

As of JUnit 5, @BeforeClass and @AfterClass are no longer available (read 5th bullet point in migration tips section). Instead, you must use @BeforeAll and @AfterAll.

You can first create a TestEnvironment class which will have at two methods (setUp() and tearDown()) as shown below:

public class TestEnvironment {
    @BeforeAll
    public static void setUp() {
        // Code to set up test Environment
    }

    @AfterAll
    public static void tearDown() {
        // Code to clean up test environment
    }
}

Then you can extend this class from all the test classes that needs this environment setup and tear down methods.

public class BananaTest extends TestEnvironment {
    // Test Methods as usual
}

If your Java project is modular, you might need to export the package (let's say env) containing the TestEnvironment class in the module-info.java file present in the src/main/java directory.

module Banana {
    exports env;
}

I am using this technique in one of my projects and it works! (see screenshot below)

Screenshot of working Test Class

Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Saptarshi Sarkar