Skip to toolbar

TestNG – 6 || Use of @BeforeMethod and @AfterMethod.

As per the names, BeforeMethod and AfterMethod annotations get executed for each test method/case in a class file.

Please note, that methods defined under @BeforeMethod and @AfterMethod are not considered as Test Cases. The result would be generated according to the methods defined under @Test annotations only.

BeforeMethod and AfterMethod Annotation
BeforeMethod and AfterMethod Annotation

BeforeMethod and AfterMethod

Sample program to understand the usage of these annotations.

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
 * @author ashok.kumar
 * Sample program to understand the usage of @BeforeMethod and @AfterMethod.
 */
public class BeforeAfterMethod 
{
	@BeforeMethod
	public void login()
	{
		System.out.println("User logged in to website.");
	}
	
	@Test(priority=1)
	public void getBlogsCount()
	{
		System.out.println("Extract total count of blogs.");
	}
	
	@Test(priority=2)
	public void myProfile()
	{
		System.out.println("User Profile get opened.");
	}
	
	@Test(priority=3)
	public void search()
	{
		System.out.println("Search Result get populated.");
	}
	
	@AfterMethod()
	public void logout()
	{
		System.out.println("User Logged out from the website.");
	}
}
Console Result
Console Result
  • In the above console output, observe below points:
    • The sequence of execution in format @BeforeMethod > @Test > @AfterMethod
    • The total number of test cases would be the same as the number of @Test annotations.
    • If the result of BeforeMethod is FAIL then rest of the Test Cases get SKIPPED.

Working Example

Let’s think about a scenario where we have to test a few functionalities on a website. And for each test case, we have to launch the browser and Close the browser. So, the dry run of the program would be like:

  • Test Case 1:- Launch the browser and URL > Check Profile of the author > Close browser
  • Test Case 2:- Launch the browser and URL > Get blogs count on the page > Close browser
  • Test Case 3:- Launch the browser and URL > Validate Search Functionality > Close browser
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

/*
/**
 * @author ashok.kumar
 */
public class BeforeMethod_AfterMethod_2 
{
	WebDriver driver;
	
	@BeforeMethod
	public void launchAndLogin() throws InterruptedException
	{
		System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
		driver=new ChromeDriver();
		driver.get("http://www.allinoneblogs.com");
		driver.manage().window().maximize();
		
		//Please comment below code if there is no Subscribe pop-up box appears.
		driver.findElement(By.xpath("//*[@id=\"popup_box_close_1484\"]")).click();
		System.out.println("Browser and URL Launched.");
	}
	
	@Test(priority=1)
	public void checkProfile()
	{
		Actions action= new Actions(driver);
		WebElement profileElement=driver.findElement(By.xpath("//*[@id=\"text-5\"]/div/p[2]/a[1]"));
		action.moveToElement(profileElement);
		action.click();
		action.perform();
		System.out.println("Profile Page opened.");
	}
	
	@Test(priority=2)
	public void getBlogsCount()
	{
		List<WebElement> blogElements=driver.findElements(By.xpath("//*[@id=\"lps-c64a26c4197944c0a82ce287589aa330\"]/article[1]/a/h3"));
		System.out.println("Blogs Count: "+blogElements.size());
	}
	
	@Test(priority=3)
	public void searchBlog() throws InterruptedException
	{
		Thread.sleep(1000);
		String searchKey="TestNG";
		driver.findElement(By.xpath("//*[@id=\"search-3\"]/form/label/input")).sendKeys(searchKey);
		driver.findElement(By.xpath("//*[@id=\"search-3\"]/form/label/input")).sendKeys(Keys.ENTER);
		System.out.println("Search Result Displayed.");
		
	}

	@AfterMethod
	public void closeBrowser() throws InterruptedException
	{
		// Paused execution for a second, to observe the progress.
		Thread.sleep(1000);
		driver.quit();
		System.out.println("Browser Closed.");
	}
}
Console Output

Related Links:

Java Basics:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:

Excel:


1723total visits,5visits today

Leave a Reply

Your email address will not be published. Required fields are marked *

Site Statistics

  • Users online: 0 
  • Visitors today : 9
  • Page views today : 10
  • Total visitors : 48,117
  • Total page view: 66,252

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.