How to use TestNG annotations with Selenium Webdriver

In this you will learn the real use of TestNG annotations covered in previous post with Selenium Webdriver scripts.

Code example:
package com.techlistic.selenium;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestNGAnnotations2 {
 WebDriver driver;
 public void setupClass() {
  // Set Chrome driver property
  System.setProperty("", "D:\\mydir\\chromedriver.exe");
  // Launch chrome browser
  driver = new ChromeDriver();

  // Opening Browser URL and maximize it
 public void setupMethod() {
  // Webdriver Code for login

 public void test_HomePage() {
  // Webdriver code to test some functionality on Home page

 public void test_UsersPage() {
  // Webdriver code to test some functionality on Users page

 public void teardownMethod() {
  // Webdriver Logout code

 public void teardownClass() {
  // Close all webdriver instances


1. @Test - This annotation is used with test methods.

2. @BeforeClass - If this annotation is used with some method then it would be executed only once before all test methods or you can say when the class is about to be executed then @BeforeClass executes. It is generally used for setup method for class. E.g.,
  • Let's say your class has 10 test methods
  • And you want to launch browser only once at the beginning and use the same browser instance for all test methods
  • Then launch browser in you setup_class method with @BeforeClass on top of it.
3. @BeforeMethod/@AfterMethod - Use this method for setup method to be called before every test. Like in above example, we are logging in before every test method and logging out after every method.

4. @AfterClass - Use this annotation for teardown class method. For e.g., in above example we used it for closing all the browser instances at the end of executing all the test methods.

Hope it helps!

For list of all TestNG (with Selenium Webdriver) posts click here: TestNG Posts

Subscribe to Facebook Group
Join Telegram channel of this website at
Feel free to ask queries or share your thoughts in comments or email me.


Popular posts from this blog

List of Selenium Demo Websites for Practice

How to learn Selenium Webdriver on your own online