Discover how a few simple annotations can save you hours of tedious test setup and cleanup!
Why TestNG annotations (@Test, @BeforeMethod, @AfterMethod) in Selenium Java? - Purpose & Use Cases
Imagine running a web test where you have to open the browser, log in, check a feature, then close the browser manually every single time you want to test something new.
You write the same setup and cleanup steps again and again for each test.
This manual way is slow and boring.
You might forget to close the browser or skip logging in, causing errors.
Repeating code wastes time and makes tests hard to maintain.
TestNG annotations like @Test, @BeforeMethod, and @AfterMethod automate setup and cleanup.
You write the login once in @BeforeMethod, the logout or close browser in @AfterMethod, and your test logic in @Test.
TestNG runs them in order for each test automatically.
public void testFeature() {
openBrowser();
login();
checkFeature();
logout();
closeBrowser();
}@BeforeMethod
public void setup() {
openBrowser();
login();
}
@Test
public void testFeature() {
checkFeature();
}
@AfterMethod
public void cleanup() {
logout();
closeBrowser();
}This lets you write clean, reusable tests that run smoothly and reliably every time.
Think of testing a shopping cart: you open the site and log in before each test, add items in the test, then log out and close the browser after.
TestNG annotations handle this flow automatically.
Manual test setup and cleanup is repetitive and error-prone.
TestNG annotations automate running setup before and cleanup after each test.
This makes tests easier to write, read, and maintain.