Video in progress

Junior 🧪 Testing

Why is a method marked with @BeforeAll usually static?

By default JUnit 5 creates a new instance of the class for every test. @BeforeAll runs once before all the tests, when no instance exists yet, so it has to be static.

📖 Answer

@BeforeAll is for expensive work done once for the whole class: for example, reading a big test file or preparing a heavy object.

class ReportParserTest {

    static String bigCsv;

    @BeforeAll
    static void loadOnce() throws IOException {
        bigCsv = Files.readString(Path.of("src/test/resources/report.csv"));
    }

    @Test
    void satrlar_soni_togri() {
        assertEquals(1000, ReportParser.parse(bigCsv).size());
    }
}

If it isn't static, JUnit throws a JUnitException and the tests never start.

The exception: if you put @TestInstance(TestInstance.Lifecycle.PER_CLASS) on the class, JUnit creates a single instance and @BeforeAll can be a regular (non-static) method. This is common in Kotlin.

Be careful: if the tests modify an object prepared in @BeforeAll, they start affecting each other. Put only read-only things there.