java – @BeforeClass vs static {}
I'm writing some test cases using JUnit I need to initialize some static variables that will be used for all test cases in this class
For this, I can use
>Static initialization block or static method of > @ beforeclass
What are the advantages of using more than one?
Solution
The semantics are very different for @ beforeclass or static initializers
Static initializers are called by the JVM, not by JUnit If an exception is thrown in the static initializer, the test framework may not be able to catch and report the exception In addition, the call time of the static initializer is not clearly defined compared with the @ beforeclass method It will only run once in its first actual use of the class loader, such as accessing static properties, static methods, or one of its constructors Sometimes it's hard to figure out what this is (if you don't use inheritance: one day you or your colleagues may refactor your test cases. If not today, the choice of static initializers may introduce annoying bugs in the future)
On the other hand, run @ beforeclass. Before running the tests for each class If a class will be subject to different tests, for example, due to inheritance based tests, the static initializer will run only for the first test using this class This means that your test order depends on what you don't want
Note that the semantic difference between the two options is greater than that between constructors using @ before or testing As a final argument, consider the documentary value of annotations It makes your intentions easier to read
The only exception to this rule is constant These should be initialized within their declarations to keep the code concise and to respect compile time constants If your value is mutable, you should never use static values at all Again, changing the variable values in the test introduces an order dependency on your test, which should be avoided
TL; Dr: use @ beforeclass!