Learn How to Use TestNG Annotations in Selenium (with 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 this article, I am going to focus on the importance of different types of annotations and their usage. 

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

Testng annotations in Selenium

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


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 following:

  • BeforeSuite
  • BeforeTest
  • BeforeClass
  • BeforeMethod
  • Test Case 1
  • AfterMethod
  • BeforeMethod
  • Test Case 2
  • AfterMethod
  • AfterClass
  • AfterTest
  • AfterSuite


public class test {

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

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

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

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

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

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

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

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

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

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


We can break the test script process in to below steps:

  1. Write the business logic of your test and insert above TestNG annotations in your code
  2. Add the 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.

Below are the lists of attributes that we can pass 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 data provider. In our case dataProvider class name is “Hello”.
  • dependsOnGroups: It 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: It is the description for the method. Eg: @Test(description = “test method”)
  • invocationCount: It 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 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


public class TestSuiteSetup () {

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

@AfterSuite(alwaysRun = true)
public void tearDown() {


#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


@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(){

#4) @BeforeMethod and @AfterMethod

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


@BeforeMethod(description="connect to database")

public void beforemethod() throws SQLException{

//check database connection is up
String databaseurl = "jdbc:oracle://";
DriverManager.getConnection(databaseurl, "username", "password");
@AfterMethod(description="close database connection")

public void aftermethod() throws SQLException{
//check database connection is closed
String databaseurl = "jdbc:oracle://";
Connection connect = DriverManager.getConnection(databaseurl, "username", "password");


#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


@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 below:

Syntax error, annotations are only available if 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 is solved

Option #2:

  • Go to 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 is solved

Option #3:

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


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 in test method. In 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 of any comments or questions.

Related Post

Leave a Reply

Your email address will not be published.