The JUnit API states the following:
"Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class."
Can we not avoid the repetition of this expensive setup using a static initializer which comes with Java itself? We can; but the BeforeClass offers one more additional feature. You can tailor-call the required setup call when you want to modularize your test cases by introducing inheritance. The below code and output will help you understand it more clearly.
The output if you run the test:
inside static of class org.sudhin.statictest.BaseTest
inside @BeforeClass of class org.sudhin.statictest.BaseTest
inside static of class org.sudhin.statictest.Test1
inside @BeforeClass setupForTest of class org.sudhin.statictest.Test1
inside test method of class org.sudhin.statictest.Test1