What is the main difference between
@Beforeand@BeforeClass- and in JUnit 5
@BeforeEachand@BeforeAll
- and in JUnit 5
@Afterand@AfterClass
According to the JUnit Api @Before is used in the following case:
When writing tests, it is common to find that several tests need similar objects created before they can run.
Whereas @BeforeClass can be used to establish a database connection. But couldn't @Before do the same?

The code marked
@Beforeis executed before each test, while@BeforeClassruns once before the entire test fixture. If your test class has ten tests,@Beforecode will be executed ten times, but@BeforeClasswill be executed only once.In general, you use
@BeforeClasswhen multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from@BeforeClassinto@Before, but your test run may take longer. Note that the code marked@BeforeClassis run as static initializer, therefore it will run before the class instance of your test fixture is created.In JUnit 5, the tags
@BeforeEachand@BeforeAllare the equivalents of@Beforeand@BeforeClassin JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.