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.

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

  • BeforeSuite
  • BeforeTest
  • BeforeClass
  • BeforeMethod
  • Test Case 1
  • AfterMethod
  • BeforeMethod
  • Test Case 2
  • AfterMethod
  • 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 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

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 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 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.

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 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.

Recommended reading

7 comments ↓

#1 zishan

Nice article.
Can you help me with testng.xml test tag. here is my query.
http://stackoverflow.com/questions/34769802/automation-testing-utilityatu-reporting-not-working-with-multiple-test-in-test

#2 Rahul Suryavanshi

thanks for sharing. can you also post the results of parsing?

#3 Abhishek Verma

Very nice article. I learn a lot.

#4 Shishir

Hey GUYS

SENT U 20 email to confirm receipt of payment and send me link to videos . Still waiting your response

#5 Shrinivas

@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

#6 Mounica

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?

#7 Saurabh Dhingra

Very Well Explained..!! Thanks :)

Leave a Comment