Niraj Sonawane
Niraj Sonawane

Reputation: 11115

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.

Upvotes: 0

Views: 2697

Answers (2)

avandeursen
avandeursen

Reputation: 8678

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.

Upvotes: 4

Arho Huttunen
Arho Huttunen

Reputation: 1131

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.

Upvotes: 2

Related Questions