TestNG Annotations in Selenium with Examples

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated May 9, 2025

In this article, I am going to focus on how to use TestNG Annotations in Selenium with appropriate examples.

TestNG, as most of you know, is an automation framework widely used in Selenium. It is important for all testers to understand the annotations used while working with TestNG.

To put it simply, TestNG annotations are lines of code that are inserted in the program/ business logic to control how the methods below are to be run.

In the article below, I have shared the set up used for my project. This does not necessarily have to be followed for your project.

How to Use TestNG Annotations in Selenium

Testng annotations in Selenium

The annotations differ depending on your project requirements. However, the flow of execution will be the same.

Prerequisites:

Before writing test scripts or setting up a project, we should know the hierarchy in which the annotations work. The execution will always remain the same.

For example, compile and run the below script and notice the execution order. It will be as follows:

  • BeforeSuite
  • BeforeTest
  • Before Class
  • BeforeMethod
  • Test Case 1
  • After Method
  • BeforeMethod
  • Test Case 2
  • After Method
  • AfterClass
  • AfterTest
  • AfterSuite

Example:

public class test {

@BeforeMethod
public void beforeMethod() {
System.out.println(" Before Method will execute before every test method");
}

@AfterMethod
public void afterMethod() {
System.out.println("After Method will execute after every test method ");
}

@BeforeClass
public void beforeClass() {
System.out.println("Before Class will always execute prior to Before Method and Test Method ");
}

@AfterClass
public void afterClass() {
System.out.println("After Class will always execute later to After Method and Test method");
}

@BeforeTest
public void beforeTest() {
System.out.println("Before Test will always execute prior to Before Class, ,Before Method and Test Method ");
}

@AfterTest
public void afterTest() {
System.out.println("After Test will always execute later to After Method, After Class ");
}

@BeforeSuite
public void beforeSuite() {
System.out.println(“Before Suite will always execute prior to all annotations or tests in the suite.");
}

@AfterSuite
public void afterSuite() {
System.out.println("After suite will always execute at last when all the annotations or test in the suite have run.");
}

@Test
public void testCase1() {
System.out.println("This is my First Test Case 1");
}

@Test
public void testCase2() {
System.out.println("This is my Second Test Case 2");
}

}

We can break the test script process into the steps below:

  1. Write the business logic of your test and insert the above TestNG annotations in your code
  2. Add information about your test (e.g. the class name, the groups, methods you wish to run, etc.) in a testng.xml file.
  3. Run TestNG

But the question still remains – what information should we provide in the above annotations?

Take a look at the important steps we can achieve using the above annotations:

#1) @Test

This is the main part of our automation script where we will write the business logic, the things which we want to automate. We can pass attributes to our test method.

Given below is a list of attributes that we can pass on to our Test method:

  • alwaysRun : This is used when we want to make sure a method always runs even if the parameters on which the method depends, fails. If set to true, this test method will always run. Eg: @Test(alwaysRun = true)
  • DataProvider: TestNG DataProvider is used to provide any data for parameterization. Eg. @Test(dataProvider = “Hello”).
  • DataProviderClass: This is the class from where we pass the data to the data provider. In our case, the dataProvider class name is “Hello”.
  • DependsOnGroups: This is the list of groups this method depends on. Eg: @Test (groups = { “City” ,”State” })
  • DependsOnMethods: This command is used to execute a method based on its dependent method. Eg: @Test (dependsOnMethods = { “OpenBrowser” ,”database is up” })
  • Description: Here is the description for the method. Eg: @Test(description = “test method”)
  • InvocationCount: This refers to the number of times a method should be invoked. It will work as a loop. Eg: @Test(invocationCount = 7) . Hence, this method will execute 7 times.
  • InvocationTimeOut: This refers to the maximum number of milliseconds a method should take for all the invocationCount to complete. This attribute will be ignored if the invocationCount is not specified. Eg: @Test(invocationCount =7,invocationTimeOut = 30 )
  • priority: This command sets the priority of the test method. Lower priorities will be scheduled first. Eg: @Test(priority =1 )

#2) @BeforeSuite and @AfterSuite

In @BeforeSuite annotated method, you can setup and start selenium drivers and in @AfterSuite annotated method, you can stop Selenium drivers

Example:

public class TestSuiteSetup () {

@BeforeSuite(alwaysRun = true)
public void setupSuite() {
WebDriver driver = new FirefoxDriver();
}

@AfterSuite(alwaysRun = true)
public void tearDown() {
driver().close();
}

}

#3) @BeforeClass and @AfterClass

In @BeforeClass annotated method, you can setup your firefox properties, initialize your driver and so on and in @AfterClass annotated method, you can stop driver

Example:

@BeforeClass(description = "Set capabilities for your Firefox browser and set time it should wait for a page to load.")
 
public static void firefoxSetUp() throws MalformedURLException {
 
DesiredCapabilities capability = DesiredCapabilities.firefox();
driver = new FirefoxDriver(capability);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1920, 1080));
 
}
 
@AfterClass(description = "close your firefox driver")
 
public void afterclass(){
driver.close();
}

#4) @BeforeMethod and @AfterMethod

In @BeforeMethod annotated method, you can check the database connection before executing your test method and in @AfterMethod annotated method, you can close your data base connection

Example:

@BeforeMethod(description="connect to database")
 
public void beforemethod() throws SQLException{
 
//check database connection is up
String databaseurl = "jdbc:oracle://192.168.1.258/myDB";
DriverManager.getConnection(databaseurl, "username", "password");
}
@AfterMethod(description="close database connection")
 
public void aftermethod() throws SQLException{
//check database connection is closed
String databaseurl = "jdbc:oracle://192.168.1.258/myDB";
Connection connect = DriverManager.getConnection(databaseurl, "username", "password");
 
if(connect!=null)
connect.close();
}

#5) @BeforeTest and @AfterTest

In @BeforTest method, you can set your firefox profile preferences and in @AfterTest method, you can put some code which will generate the test result and mail it to the stake holders.

Example:

@BeforeTest (description="set your firefox profile preferences according to your project requirement")
 
public void single_run(){
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference ("browser.download.folderList",2);
firefoxProfile.setPreference ("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference ("browser.download.dir","E:\\reports\\");
firefoxProfile.setPreference ("browser.helperApps.neverAsk.saveToDisk","csv");
driver = new FirefoxDriver(firefoxProfile);
String baseUrl = "www.gmail.com";
}
 
@AfterTest (description="")
public void teardown(){
//a code which will send the test details report
}

The most important aspect that should be noted here while working with annotations is that your system should be equipped with Java 1.5 version or higher, otherwise Eclipse might show an error that annotations are not supported on your system.

Now, consider a case where your system has the right version of Java needed for annotations but the error still appears.

Something like the following:

Syntax errors and annotations are only available if the source level is 1.5 or greater.   

What will you do now? There are three options to rectify this situation.

Let’s go through it one by one:

Option #1:

  • Go to Eclipse and right click on your project
  • Select Properties
  • Click on Java Compiler
  • Make sure your Compiler Compliance Level is 1.5 or higher
  • Save the settings and your problem will be solved

Option #2:

  • Go to the Window Tab in Eclipse
  • Select Preferences
  • Click on Java and then on Compiler
  • Make sure your Compiler Compliance Level is 1.5 or higher
  • Save the settings and your problem will be solved

Option #3:

Check your Java Home Path by setting the correct Java environment path variable.

Conclusion

Through this article, we tried to discuss some of the important annotations and attributes which are frequently used by testers. However, there are more annotations in TestNG which are not frequently used, such as @AfterGroups, @BeforeGroups and so on, which are used when you are working with groups in your project test script.

So use the above annotations according to your requirements. It is always advisable not to do your project setup using a test method. In the test method, write the core business logic which is to be tested.

Make sure your system is equipped with Java 1.5 versions or higher, otherwise Eclipse might show an error that annotations are not supported on your system.

Hope this article helps you with TestNG annotations. Please do let us know in case you have any feedback or questions. We would love to hear from you. 

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • FIND ELEMENT BY TEXT

    An In-Depth Look at Selenium Find Element by Text with Example: Selenium Find Element That Contains Specific Text Selenium Find element by text is used to locate a web element using its text value. The text value is generally used when the basic element identification properties such as ID or…

  • Keyword Driven Framework In Selenium

    This Comprehensive Tutorial on Keyword Driven Framework Explains Various Components of the Framework & How to Create One in Selenium: In general, Framework is a set of guidelines, which when followed will give beneficial results. The Keyword-Driven framework is a technique to externalize keywords/actions that are used in the script…

  • Selenium TestNG Framework

    In the last few tutorials, we shed light on the basic and commonly used WebDriver commands. We also learned about the locating strategies of UI elements and their inclusion in the test scripts. Therefore, we developed our very first WebDriver Automation Test Script. Moving ahead with this tutorial, we will…

  • 9. QUERY MODIFICATION IN MONGODB

    A Detailed insight of Query Modification in MongoDB using Sort(). Cursor and its methods within MongoDB were explained in detail in our previous tutorial in this MongoDB Training series. In this tutorial, we will take an in-depth look at the Sort method in MongoDB. Sort method is used to prioritize…


READ MORE FROM THIS SERIES:



13 thoughts on “TestNG Annotations in Selenium with Examples”

  1. I instantiated the driver in Before Test annoted method and trying to user the obj. refernce in test annoted methog. But it not allowing as it throws a compilation error. I have testng libraries available for that Project. Can you please suggest me why? Both of the nmethods are in same class like it is in the first example.

    Reply
  2. Hi,
    At the end of the article,it is written as below
    “It is always advisable not to do your project setup in test method. In test method write the core business logic which is to be tested.”

    I didn’t get it.Can you please let me know the meaning of this in detail?

    Reply
  3. @Rahul – find the result

    Before Suite will always execute prior to all annotations or tests in the suite
    Before Test will always execute prior to Before Class, ,Before Method and Test Method
    Before Class will always execute prior to Before Method and Test Method
    Before Method will execute before every test method
    This is the First Test Case 1
    After Method will execute after every test method
    Before Method will execute before every test method
    This is the Second Test Case 2
    After Method will execute after every test method
    After Class will always execute later to After Method and Test method
    After Test will always execute later to After Method, After Class

    Reply
  4. dependsOnGroups: It is the list of groups this method depends on. Eg: @Test (groups = { “City” ,”State” }) — is this correct? isnt it @Test (dependsOnGroups ={ “City” ,”State” })??

    Kindly help on this query

    Reply

Leave a Comment