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
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.");
}
}

- 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.");
}
}

Related Links:
- TestNG – 1 || Introduction and benefits of TestNG Framework.
- TestNG – 2 || Installation process and a sample program of TestNG.
- TestNG – 3 || Create and execute multiple Test Cases.
- TestNG – 4 || Let’s understand @Test Annotation and attributes.
- TestNG – 5 || Understand Assertion in TestNG.
- TestNG – 6 || Use of @BeforeMethod and @AfterMethod.
- TestNG – 7 || Use of @BeforeClass and @AfterClass.
- TestNG – 8 || Creation and execution of Test Suites.
- TestNG – 9 || Let’s move deep into the Test Suites.
- TestNG – 10 || Use @BeforeTest and @AfterTest Annotations.
- TestNG – 11 || Groups attribute with @Test Annotation.
- TestNG – 12 || Use of @BeforeGroups & @AfterGroups.
- TestNG – 13 || Use of @BeforeSuite & @AfterSuite.
- TestNG – 14 || DataProvider annotation & attribute.
- TestNG – 15 || DataProvider with parameters.
- TestNG – 16 || Access data from Excel sheet using DataProvider.
- TestNG – 17 || Passing multiple Parameters in testng xml.
- TestNG – 18 || Multiple Browser and Parallel Execution in TestNG.
- TestNG -19 || Concept of Parallel Execution.
- TestNG – 20 || Run TestNG Program using main() method.
Java Basics:
- Basic Java – 1 || Understand Java before start learning JAVA.
- Basic Java – 2 || Variables and Data Types used in JAVA.
- Basic Java – 3 || Understanding Class, Objects, Methods in Java.
- Basic Java – 4 || More on methods(Return Type and Parameters)
- Basic Java – 5 || Methods- Call by Value and Call by Reference in Java.
- Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.
- Basic Java – 7 || Static Variables and Methods.
- Basic Java – 8 || Lets learn about Arrays in Java.
- Basic Java – 9 || Performing multiple operations using Java Operators.
- Basic Java – 10 || Conditions (If and Switch) in JAVA.
- Basic Java – 11 || for and for-each in Java. (Loops Part-1)
- Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)
- Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.
- Basic Java – 14 || Learn about String literals in Java.
- Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
- Basic Java – 16 || Runtime User Input using BufferedReader Class (Part-2).
- Basic Java – 17 || Runtime User Input using Console Class (Part-3).
- Basic Java – 18 || Difference between break and continue keywords.
- Basic Java – 19 || Sending Email using Java (Part-1).
- Basic Java – 20 || Sending Email with attachment using Java (Part-2).
- Basic Java – 21 || Stack memory and Heap memory in Java.
- Basic Java – 22 || Let’s learn more about String.
- Basic Java – 23 || String, StringBuffer & StringBuilder in Java.
- Basic Java – 24 || Exception Handling using Try Catch.
- File Handling | Reading data from word document(.doc or .docx) in JAVA.
- File Handling | Reading data from Excel files (.xls or .xlsx) using JAVA.
- File Handling | Writing data into an Excel(.XLSX or .XLS) File.
- File Handling | Implement formatting in Excel using Java.
- File Handling | Copy existing data from one workbook to another workbook in Java.
- File Handling | Reading data from PDF file using JAVA.
- File Handling || Traverse folders and subfolders in Java.
- File Handling || Reading and Writing data from a text file.
- File Handling || Multiple file creation using template based input data.
- Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).
- QnA || How to use Constructors in Abstract class?
- QnA | Difference between Integer and int keywords.
- QnA | Can main method be overloaded?
- QnA | How do I reverse a String/Sentence in Java?
- QnA | Perform Multiplication and Division without * or / or % operators.
- QnA | How do I get the default value of data type?
- QnA | How to split String if it contains period symbol (.) in between?
- Different ways to Reverse a String in Java.
- Copy formatting & style of cells from one sheet to another.
- Getting IP address and Hostname using InetAddress Class.
- User inputs via Command Prompt using arguments of main() method of a class.
- Program for List and ArrayList in Java.
- Useful methods and implementation under Scanner Class.
- Swapping two variable values without using any third variable.
- Difference between int x= 10 and y=010 in Java.
- Parameterized Constructors v/s Setter and Getter function in JAVA.
- Override a Static Method.
- Computer Basics -13 || Creating pivot charts/tables in Excel.
- Computer Basics -12 || Advantages of PivotCharts over Simple Charts in Excel.
- Computer Basics -11 || Using Charts in place of Data Tables in Excel.
- Computer Basics -10 || How to apply Filter in a data set in Excel?
- Computer Basics -9 || Understand and Implement Data Validation in Excel.
- Computer Basics -8 || Let’s learn the usage of MS-Excel.