0

I very much understand what @BeforeClass is. It is executed once before JUnit test run is started & @Before method is executed before every test case. My question is regarding a very old post by a very senior stackoverflow user (Péter Török 68.8k) Please refer [stackoverflow question] [1]: JUnit: using constructor instead of @Before which was posted about 2 yrs ago but on JUnit4. so I think it is still valid and true.

Here he mentions

@Before is equivalent to constructor of test class

and

JUnit creates a new instance of the test class for each @Test,

So how does JUnit manage running @BeforeClass only once which is defined inside the test class?

Community
  • 1
  • 1
Amar
  • 1,556
  • 3
  • 18
  • 28

4 Answers4

5

Methods annotated with @BeforeClass must be static. JUnit doesn't need any instance of the test class to call it.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Well, jUnit could run the method annotated with @BeforeClass at time of class loading, that is like you would implement on your own with a static initializer.

You get also the hint that jUnit is doing something like this by the fact that @BeforeClass and @AfterClass annotated methods must be static.

Matthias
  • 3,582
  • 2
  • 30
  • 41
1

That's because @BeforeClass has to be a static method. Once it is static, JUnit knows how to run it once.

Lital Kolog
  • 1,301
  • 14
  • 39
1

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. Static methods are not belongs to instances of the class. Those are properties of the class.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105