In this article, we will see testNG's annotations beforeSuite and afterSuite.
@BeforeSuite
- @BeforeSuite is an annotation used to specify a method that needs to be executed before any test method in the suite.
- This method is executed only once per suite.
- For example, if you have a suite with multiple test classes, the @BeforeSuite method will be executed only once before the execution of any test method in any of the test classes.
@AfterSuite
- @AfterSuite is an annotation used to specify a method that needs to be executed after all the test methods in the suite have been executed.
- This method is also executed only once per suite.
- For example, if you have a suite with multiple test classes, the @AfterSuite method will be executed only once after the execution of all the test methods in all of the test classes.
Example:
Consider three classes One, Two, and Three.
One:
package week4.day2;
import org.testng.annotations.Test;
public class One {
@Test
private void leafVillage() {
System.out.println("Naruto");
}
}
Two:
package week4.day2;
import org.testng.annotations.Test;
public class Two {
@Test
private void sandVillage() {
System.out.println("Gara");
}
}
Three:
package week4.day2;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class Three {
@BeforeSuite
private void akatsuki() {
System.out.println("Itachi");
}
@Test
private void leader() {
System.out.println("Pain");
}
@AfterSuite
private void mainAntagonist() {
System.out.println("Madara");
}
}
Now let us run these three classes with the testng.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="test_suite">
<test name="One">
<classes>
<class name="week4.day2.One"/>
</classes>
</test> <!-- Test -->
<test name="Two">
<classes>
<class name="week4.day2.Two"/>
</classes>
</test> <!-- Test -->
<test name="Three">
<classes>
<class name="week4.day2.Three"/>
</classes>
</test>
</suite> <!-- Suite -->
- We can see here when three classes are run, and the three class has the @before and @after suite.
- No matter what, running the methods with the annotation before and after any classes is prioritized.
- That is what happened here.