This is most confusing point in testng. Let us understand the difference between them.
@BeforeTest Will be called before any Test only..
@BeforeMethod will be called before every method
@BeforeMethod will be called before every method
Note that, not every method in a file is Test, but every Test in a file is a method.
In the above case the helper() method is only a method not a Test. Whereas toBeforeTest() and toBeforeMethod() are Test, since they are preceded with “@Test” annotation.
@BeforeTest will be executed only for the blocks of toBeforeTest() and toBeforeMethod().
Whereas @BeforeMethod will be executed for all the methods of toBeforeTest(), toBeforeMethod() as well as the helper() method
@BeforeTest is used to do setup related to bunch of tests written inside the tag as the author has mentioned.
@BeforeTest
|
@BeforeMethod
|
To execute a set-up method before any of the test methods included in the < test > tag in the testng.xml file.
|
To execute a set-up method before any of the test methods annotated as @Test.
|
Example Testng.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
<test name="test">
<classes>
<class name=".BeforetestandBeforemethod">
<methods>
<include name="toBeforeTest"></include>
<include name="toBeforeMethod"></include>
</methods>
</class>
</classes>
</test>
<methods>
</suite> <!-- Suite -->
Example Java code such as:
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class BeforetestandBeforemethod {
@BeforeTest
public void beforeTest() {
System.out.println("@BeforeTest");
}
@BeforeMethod
public void beforemethod(){
System.out.print("@BeforeMethod");
}
public void helper() {
System.out.println("Flow");
}
@Test
public void toBeforeMethod() {
helper();
System.out.println("BeforeMethod");
}
@Test
public void toBeforeTest() {
helper();
System.out.println("BeforeTest");
}
}
Execute code by TestNG, then the Output would be:
When run <include name=”toBeforeTest”></include>
Run <include name=”toBeforeMethod”></include>
Hope this helps !!!!