@BeforeClass abstract: Junit vs TestNG

Why is the @BeforeClass method in JUnit equal to static , while in TestNG its non-static ? TestNG was designed as an improvement over JUnit , so why did they choose this implementation method?

Since @BeforeClass launched only once, therefore making it static more reasonable than making it non-static. Also in TestNG, on which instance is the @BeforeClass method @BeforeClass ? Can someone give an example for a better understanding?

+7
java junit testng
source share
2 answers

The main difference between JUnit and TestNG is the instantiation of the test class. JUnit always creates a new instance of the test class for each test method run. TestNG creates only one instance of the test class, and then runs all the testing methods for this instance.

The JUnit approach guarantees the independence of all testing methods. It just doesn't matter in which order they run. In addition, all instance fields are always the same for each test method. Data initialization, which is common to all testing methods, must take place at the class level, so it must be static. For this reason, the @BeforeClass method must be static.

TestNG approval does not guarantee independence. In fact, you cannot use the instance field in the same way as in JUnit tests. If you change such a field in one test method, the changed value is still observed in another test method. However, this behavior also has an advantage: sometimes there are some dependencies between some testing methods. Using TestNG, the tester can express them.

Due to the single-level approach of TestNG, setting up @BeforeClass can also be a non-stationary method, but it still only executes once. It was a constructive solution, but testers using TestNG should be aware of this.

+8
source share

Creating a static or non-static method has nothing to do with the fact that it can call this method only once at the beginning. You can call the static method as many times as you want. You can call the non-static method exactly one. There is no necessary correlation between them: static and a call once. At least I don’t know about any direct consequences of creating a static method that allows it to be called exactly once. static rightly associated with one class, but not with one call.

Creating a static method prevents access to non-stationary class members. But with the non-static @BeforeClass method, you can also access non-stationary members, giving you more options to access class variables. Perhaps this is why testng removed the limitation of the @BeforeClass method to static.

+1
source share

All Articles