Why the @BeforeClass
method in JUnit
is static
whereas in TestNG
its non-static
? TestNG
was developed as an improvement over JUnit
, so why did they choose this way of implementation?
Since @BeforeClass
runs only once, so making it static
makes more sense than making it non static. Also in TestNG, on which instance the @BeforeClass
method is called? Can someone cite an example for better understanding?
The main difference between JUnit and TestNG is the test class instantiation. JUnit always creates a new instance of the test class for each test method run. TestNG only creates one test class instance and then runs all test methods of this instance.
The JUnit approach guarantees the independency of all test methods. It just does not matter, in which order they run. Additionally, all instance fields are always setup the same for each test method. Initializing data, that is common for all test methods, must take place at the class level, thus it must be static. This is the reason, why the @BeforeClass method must be static.
The TestNG approch does not guarante the independency. In fact, you cannot use an instance field in the same manner as in JUnit tests. If you change such a field in one test method, the changed value is still observabl in another test method. However, this behavior has also an advantage: Sometimes there are dependencies between some test methods. With TestNG, a tester can express them.
Because of the one-instance-approach of TestNG, the @BeforeClass setup can also be a non-static method, but it is still run only once. It was a design decision, but testers using TestNG must be aware of that.
Making a method static or non-static has nothing to do with being able to invoke that method only once at the beginning. You can call a static method as many times as you want. You can call a non-static method exactly one. There is no necessary correlation between the two : being static and invoking once. At least, I am not aware of any direct consequence of making a method static which enables it to be invoked exactly once. static
is rightly associated with single class, but not with single invocation.
Making a method static prevents it from accessing non-static members of the class. But with having a non-static @BeforeClass
method, you can also access non-static members, there by giving you more scope to access class variables. Perhaps this is the reason why testng removed the restriction of @BeforeClass
method being static.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With