@BeforeClass vs static{}

前端 未结 4 680
难免孤独
难免孤独 2020-12-30 00:18

I am writing some test cases using JUnit. I need to initialize some static variables which will be used for all the test cases in that class.

For this I can use eith

4条回答
  •  醉酒成梦
    2020-12-30 01:05

    Here's a couple of considerations that could be taken into account when deciding whether to use the static initialization block or @BeforeClass:

    1. @BeforeClass is the antagonist of @AfterClass. So if you do initializations that require cleaning up later (like opening external resources) it would be better (from a semantic point of view) to use the annotated methods.
    2. If you do complex initializations that might throw checked exceptions it's much more comfortable to use @BeforeClass, because you don't have to catch and wrap it into an unchecked exception.
    3. If you want to use constant semantics (private static final String VARIABLE) with complex initialization, you will have no choice but to use the static initialization block or a static method.

    There is a related post on SO: unit testing - What's the difference between using @BeforeClass and using instance or static variable in JUnit 4 Java?

提交回复
热议问题