Both annotations runs before the @test in testNG then what is the difference between two of them.
I know there have already been several good answers to this question, I just wanted to build on them to visually tie the annotations to the xml elements in testng.xml, and to include before/after suite as well.
I tried to keep it as newbie friendly as possible, I hope it helps.
My java example is basically just a reformatted version of Ishita Shah's code.
BeforeAfterAnnotations.java (assumes this file is in a package called "test")
package test;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class BeforeAfterAnnotations
{
@BeforeSuite
public void beforeSuiteDemo()
{
System.out.println("\nThis is before a start tag.");
}
@BeforeTest
public void beforeTestDemo()
{
System.out.println("\tThis is before a start tag.");
}
@BeforeClass
public void beforeClassDemo()
{
System.out.println("\t\tThis is before a start tag.\n");
}
@BeforeMethod
public void beforeMethodDemo()
{
System.out.println("\t\t\tThis is before a method that is annotated by @Test.");
}
@Test
public void testADemo()
{
System.out.println("\t\t\t\tThis is the testADemo() method.");
}
@Test
public void testBDemo()
{
System.out.println("\t\t\t\tThis is the testBDemo() method.");
}
@Test
public void testCDemo()
{
System.out.println("\t\t\t\tThis is the testCDemo() method.");
}
@AfterMethod
public void afterMethodDemo()
{
System.out.println("\t\t\tThis is after a method that is annotated by @Test.\n");
}
@AfterClass
public void afterClassDemo()
{
System.out.println("\t\tThis is after a end tag.");
}
@AfterTest
public void afterTestDemo()
{
System.out.println("\tThis is after a end tag.");
}
@AfterSuite
public void afterSuiteDemo()
{
System.out.println("This is after a end tag.");
}
}
testng.xml (testng.xml --> run as --> TestNG Suite)
Output to console
[RemoteTestNG] detected TestNG version 7.0.0
This is before a start tag.
This is before a start tag.
This is before a start tag.
This is before a method that is annotated by @Test.
This is the testADemo() method.
This is after a method that is annotated by @Test.
This is before a method that is annotated by @Test.
This is the testBDemo() method.
This is after a method that is annotated by @Test.
This is before a method that is annotated by @Test.
This is the testCDemo() method.
This is after a method that is annotated by @Test.
This is after a end tag.
This is after a end tag.
This is after a end tag.
===============================================
Before/After Annotations Suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================