Search code examples
junitjunit4junit5

What is difference between BeforeClass (Junit 4 ) and BeforeEach(Junit5)


Both the annotations are used to signal that the annotated method should be executed before each Test method in the current test class.

Then why do we have changed the annotation from @BeforeClass - Junit 4 To @BeforeEach Junit 5 ?

is there anything additional that have been added in junit 5 that i am missing ?

Similar case for other annotations.


Solution

  • The main functionality added is more fine-grained control over the Test Instance Lifecycle, for example through @TestInstance annotations. I presume this was one of the reasons to change the names of the old @Before and @BeforeClass annotations.

    The old (JUnit4) @Before and the new (JUnit5) @BeforeEach are similar in that they are executed anew before every @Test method in a test class. So if your class has 10 test methods, the @BeforeEach method is executed 10 times.

    The old (JUnit4) @BeforeClass and the new (JUnit5) @BeforeAll are similar in that they are both executed just once, before any of the tests in the class. So even if your class has 10 tests, the @BeforeAll method is executed just once.

    The suggestion made in the question that @BeforeClass was renamed to @BeforeEach is thus incorrect.

    For more information, see also this question on the difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll.