Difference between @Before class and Before Test
@BeforeTest-The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
@BeforeClass-The annotated method will be run before the first test method in the current class is invoked.
Have a look on below example
Lets create a java class ex: beforeclassexample
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
publicclass beforeclassexample {
@BeforeClass
publicvoid BeforeclassSample(){
System.out.println("This Method will Execute Before Class in beforeclassexample ");
}
@AfterClass
publicvoid AfterClassSample(){
System.out.println("This Method will Execute After Class in beforeclassexample");
}
@Test
publicvoid TestMethodExample(){
System.out.println("This is TestMethod example1 in beforeclassexample");
}
@Test
publicvoid TestMethodExample1(){
System.out.println("This is TestMethod exanple2 in beforeclassexample");
}
}
Create a another java file ex: beforetestexample
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
publicclass beforetestexample {
@BeforeTest
publicvoid BeforeTestSample(){
System.out.println("This Method will Execute Before Test in beforetestexample");
}
@AfterTest
publicvoid AfterTestSample(){
System.out.println("This Method will Execute After Test in beforetestexample");
}
@Test
publicvoid TestMethodExample3(){
System.out.println("This is TestMethod exanple3 in beforeclassexample");
}
}
TestNG.xml file
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsuiteSYSTEM"http://testng.org/testng-1.0.dtd">
<suitename="Suite"parallel="none">
<testname="Test">
<classes>
<classname="beforetestexample"/>
<classname="beforeclassexample"/>
</classes>
</test><!-- Test -->
</suite><!—Suite -->
Results
Here First it will execute @BeforeTest Method before @Test method and @after Test method will execute after all run the annotations (@Before class, @After Class and @Test)
Look in to the TetNG.xml
<test> tag is wrapped by @BeforeTest and @AfterTest --à<testname="Test">
<class> tag is wrapped by @BeforeClass and @AfterClass
<classname="beforetestexample"/>
<classname="beforeclassexample"/>
Lets see another example :
TestNG.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsuiteSYSTEM"http://testng.org/testng-1.0.dtd">
<suitename="Suite"parallel="none">
<testname="Test1">
<classes>
<!-->class name="TestNGExample"/-->
<classname="beforetestexample"/>
<classname="beforeclassexample"/>
</classes>
</test><!-- Test -->
<testname="Test2">
<classes>
<!-->class name="TestNGExample"/-->
<classname="beforetestexample"/>
<classname="beforeclassexample"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->
In the above TestNG.xml we have two <test> tags
Results
Here TestMethod “TestMethodExample3” executes twice because in TestNG.xml file we are using Two <test> tags
<testname="Test1">
<testname="Test2">
Comments
Post a Comment