This article will witness the TestNG's beforemethod and aftermethod annotations.
BeforeMethod:
- The @BeforeMethod annotation is called before the execution of each method.
- For example, there are five tests, and the third is @BeforeMethod.
- The third method is executed first and then moves on to the rest in order.
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.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class PopUp {
@BeforeMethod
private void test1() {
System.out.println("I came Before");
}
@Test
public void popUp() throws Throwable {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.programsbuzz.com/");
driver.manage().window().maximize();
Thread.sleep(3000);
List<WebElement> elementTexts = driver.findElements(By.xpath("//div[@class='header__main__left']"));
for (WebElement webElement : elementTexts) {
System.out.println(webElement.getText());
}
}
}
- We can see here the test1 method has been run before the popup method.
AfterMethod:
- @AfterMethod is the opposite of what BeforeMethod does.
- This method is run after each method in a TesNG test.
- For example, we have four tests; the second uses @AfterMethod annotation.
- The second method is run after the execution of each test method.
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.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class PopUp {
@AfterMethod
private void test2() {
System.out.println("I come After");
}
@Test
public void popUp() throws Throwable {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.programsbuzz.com/");
driver.manage().window().maximize();
Thread.sleep(3000);
List<WebElement> elementTexts = driver.findElements(By.xpath("//div[@class='header__main__left']"));
for (WebElement webElement : elementTexts) {
System.out.println(webElement.getText());
}
}
}
- We can see here popUp method has run, and then after that, test2 has been executed since it has the @AfterMethod annotation.
- Log in to post comments