|
@BeforeClass and @AfterClass |
@Before and @After |
| Number of occurrences |
Only one time can appear in a class |
can occur multiple times in a class, that is, you can add these two annotaion tags before the declaration of multiple methods, and the order of execution is indeterminate |
| Method Name Restrictions |
Method name does not limit |
Method name does not limit |
| Number of runs |
Run only once in a class |
Run once before or after each test method |
| Execution order |
@BeforeClass method that identifies the annotation in the parent class will be executed before the method that identifies the annotation in the current class. @AfterClass method that identifies the annotation in the parent class will execute after the method that identifies the annotation in the current class |
@Before method that identifies the annotation in the parent class will be executed before the method that identifies the annotation in the current class. @After method that identifies the annotation in the parent class will execute after the method that identifies the annotation in the current class |
| Static |
Must be declared as public static |
Must be declared as public and not static |
| @After/@AfterClass whether to perform |
All methods that are identified as @afterclass are bound to be executed, even if the method that is identified as @beforeclass throws an exception. |
All methods identified as @after are bound to be executed, even if the method that identifies the @Before or @Test throws an exception. |
| Cooperate with @repeat |
Execute only once |
Executes multiple times |
Note
- @BeforeClass and @AfterClass are very effective for allocating or releasing resources that are "expensive", because they are only executed once in the class. In contrast, using @before and @after is also a wise choice for resources that need to be initialized before each run, or need to be cleaned after running.
- JUNIT4 and Junit3 have a certain difference, in Junit3, the test method must start with test, that is, the method is Testxxx (), there is no such restriction in JUNIT4. Because the annotation (annotation) @Test can be used in JUNIT4 to specify the test method. However, you do not inherit the TestCase parent class in JUNIT4, and if you use inheritance, the annotations of JUNIT4 will be invalidated. JUNIT4 does not inherit testcase, nature cannot directly use methods such as assertequal, if you want to use assertions must be directly static references, that is, assert.assertequal (int, int) this way.
Comparison between @after @before of JUNIT4 in @afterclass @BeforeClass