0

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.

Niraj Sonawane
  • 6,954
  • 7
  • 49
  • 76
  • 1
    No, that's not what BeforeClass is for. Read the javadoc. But names have been changed because... they thought the new names were better. Since it's a new, incompatible version, why not change the names? – JB Nizet Dec 27 '17 at 13:49
  • 4
    `@Before` was renamed to `@BeforeEach` (and `@BeforeClass` was renamed to `@BeforeAll`). As you already mentioned, they are "executed before each test method". So this is a good new name. – Roland Weisleder Dec 27 '17 at 14:07
  • Thanks for checking this. BeforeClass is also used to run once before any of the test methods in the class so both are same. it's of if they have just changed the name.i wanted to know if they have added any additional stuff in new annotations – Niraj Sonawane Dec 27 '17 at 14:12

2 Answers2

3

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.

avandeursen
  • 7,747
  • 3
  • 36
  • 48
2

There are some changes related that require the test class to be annotated with @TestInstance(Lifecycle.PER_CLASS) first. This will create a new test instance once per test class instead of per method.

As a result, you can use @BeforeAll and @AfterAll for non-static methods as well as on interface default methods. It also allows you to use @BeforeAll and @AfterAll in @Nested test classes.

If you use Lifecycle.PER_CLASS you have to remember that if your tests rely on state stored in instance variables you might have to reset that state in @BeforeEach and @AfterEach.

Arho Huttunen
  • 806
  • 6
  • 15