The @beforeTest and @afterTest annotations execute pre-test and post-test operations at the suite level.
beforeTest
- @BeforeTest annotation is used to perform pre-test setup operations that need to be executed before the start of the test.
- It is executed once before all the test methods in the suite.
- The @BeforeTest annotation sets up the environment for the test cases to run.
- For example, you can use this annotation to create objects, initialize data, or start a server.
@BeforeTest
public void setUp() {
// code to set up the environment for the test cases to run
}
afterTest
- @AfterTest annotation is used to perform post-test cleanup operations that need to be executed after completing all the test methods in the suite.
- It is executed once after all the test methods in the suite. The @AfterTest annotation cleans up the environment after completing the test cases.
- For example, you can use this annotation to close the database connections, delete temporary files, or shut down a server.
@AfterTest
public void tearDown() {
// code to clean up the environment after the test cases have been executed
}
Example:
package week4.day2;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class PopUp {
ChromeDriver driver;
@BeforeTest
private void setUp() throws InterruptedException {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://www.programsbuzz.com/");
driver.manage().window().maximize();
Thread.sleep(3000);
}
@AfterTest
private void tearDown() {
driver.quit();
}
@Test(retryAnalyzer = Retry.class)
public void popUp() throws Throwable {
List<WebElement> elementTexts = driver.findElements(By.xpath("//div[@class='header__main__left']"));
for (WebElement webElement : elementTexts) {
System.out.println(webElement.getText());
}
}
}
- This test is a perfect example of the annotation used before and after the test.
- In the beforeTest, we used it as the block to set up the web driver and launch the URL.
- afterTest is used to close the browser.
- This is how we can effectively use the before and after test annotations in TestNG.