TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Important TestNG Annotations for Selenium
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

Important TestNG Annotations for Selenium

Last updated: Jun 03, 2024 12:39 pm
By Harsh S.
Share
15 Min Read
Must-know TestNG Annotations for Selenium Webdriver Project
Must-know TestNG Annotations
SHARE

In our last post on TestNG, we explained the three unique ways to install the TestNG plugin in Eclipse IDE. Now the next important topic is to learn about the TestNG annotations. TestNG is a Java testing framework and library. It’s commonly used in conjunction with Selenium for automated web testing.

Contents
What is an Annotation?Advantages of Using AnnotationsList of TestNG Annotations@Test Annotation@BeforeTest Annotation@AfterTest Annotation@BeforeMethod Annotation@AfterMethod Annotation@Parameters Annotation@DataProvider Annotation@BeforeClass Annotation@AfterClass Annotation@BeforeGroups Annotation@AfterGroups Annotation@BeforeSuite Annotation@AfterSuite Annotation@Factory Annotation@Listeners Annotation

Understand the Important Annotations in TestNG

There are multiple TestNG annotations that you can use for different tasks. It is essential to know each of the annotations so that you can apply them correctly while working on a TestNG Selenium Webdriver project. Let’s see what are the TestNG annotations for Selenium Webdriver and what is their objective.

What is an Annotation?

Annotations are nothing but a piece of instruction for the compiler that you apply to classes, methods, or variables in your Java code. It is a predominant feature of the TestNG framework. They control the execution sequence of the test code and test methods.

We have compiled a list of primary TestNG annotations along with a little detail about each of them. We believe the below list should be at your fingertips. If you remember it, it could come quite handy during Job interviews.

Advantages of Using Annotations

There are many benefits of using TestNG annotations in a project.

  • Provides more delicate control over test execution
  • Allows test case grouping and prioritization
  • Enables parallelization of tests
  • Support parameter testing
  • Can connect to external data sources
  • Have an excellent report-generating ability
  • Strongly typed means strong error-checking

List of TestNG Annotations

IndexTestNG AnnotationsDescription
1.@TestAttaches a class or a method to become part of the test.
2.@BeforeTestAttaches a class or a method to become part of the test.
3.@AfterTestHalts a method from execution till all the test methods finish their execution.
4.@BeforeMethodAllows a method to run before executing any of the @test annotated methods.
5.@AfterMethodAllows a method to take off after all of the @test annotated methods finish their execution.
6.@ParametersInstructs the method to run before any test method related to the classes that are inside the <test> tag as per the <testng.xml> file.
7.@DataProviderIt marks a method as a data source for the test. Every @DataProvider annotated method must always return the value as <Object[ ][ ]>.
8.@BeforeClassThe method annotated with @BeforeClass gets executed once before the first test method of the current class.
9.@AfterClassThe method annotated with @AfterClass gets run once after finishing all the test methods in the current class.
10.@BeforeGroupsIt sets up the method to run before the first test method belonging to any of the groups involved in the execution.
11.@AfterGroupsIt sets up the method to run after the execution of all the test methods belonging to any of the groups participating in the test.
12.@BeforeSuiteAny such method will get called before any of the suites runs from the test.
13.@AfterSuiteAny such method will stay its execution until all other methods in the current test suite get executed.
14.@FactoryYou use it to execute any specific group of test cases with different values. It returns an array of test class objects as the <Object[ ]>.
15.@ListenersYou can use them with the test classes for the logging function.
Important TestNG Annotations for Selenium

@Test Annotation

Use the @Test annotation to mark methods as test methods in TestNG. Inside these methods, you can write your test logic and assertions.

import org.testng.Assert;
import org.testng.annotations.Test;

public class SimpleTestNGTest {
@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}
}

@BeforeTest Annotation

This annotation executes a method before any test method in the current test tag in the TestNG XML file. Hence, use it for setup activities that usually occur before the test.

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SimpleTestNGTest {
@BeforeTest
public void setUp() {
// Code to set up resources, initialize variables, etc.
System.out.println("Setting up before tests run.");
}

@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}
}

@AfterTest Annotation

The @AfterTest executes a method after all the test methods in the current test tag in the TestNG XML file have run. Use it for post-test cleanup tasks.

import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@AfterTest
public void tearDown() {
// Code to clean up resources, reset variables, etc.
System.out.println("Cleaning up after tests run.");
}

@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}
}

@BeforeMethod Annotation

This annotation calls a method before each test method in the current TestNG class. Hence, use it for tests that require checking some conditions before execution.

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@BeforeMethod
public void setUp() {
// Code to set up resources, initialize variables, etc.
System.out.println("Setting up before each test method.");
}

@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}
}

@AfterMethod Annotation

@AfterMethod calls a method after each test method in the current class. Hence, it works best for the cleanup of individual tests.

import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@AfterMethod
public void tearDown() {
// Code to clean up resources, reset variables, etc.
System.out.println("Cleaning up after each test method.");
}

@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}
}

@Parameters Annotation

@Parameters annotation is used to pass parameters from the TestNG XML file to test methods. It is helpful when you have to run the same test with different data.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<parameter name="a" value="5"/>
<parameter name="b" value="3"/>
<classes>
<class name="SimpleTestNGTest"/>
</classes>
</test>
</suite>
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@Test
@Parameters({"a", "b"})
public void plusTest(int a, int b) {
int sum = a + b;
Assert.assertEquals(sum, 8);
}
}

@DataProvider Annotation

@DataProvider annotation creates a method that supplies data to a test method in the TestNG class. Hence, use it when you have to take input from external data sources and pass it to your tests.

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {

@DataProvider(name = "plusData")
public Object[][] provideData() {
return new Object[][] {
{ 5, 3, 8 },
{ 2, 2, 4 },
{ -1, 1, 0 }
};
}

@Test(dataProvider = "plusData")
public void plusTest(int a, int b, int expectedSum) {
int sum = a + b;
Assert.assertEquals(sum, expectedSum);
}
}

@BeforeClass Annotation

This annotation executes a method before the first test method in the current class runs. It ensures running the setup tasks once before any test methods run.

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@BeforeClass
public void setUpBeforeClass() {
// Code to set up resources, initialize variables, etc.
System.out.println("Setting up before the first test method runs.");
}

@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}
}

@AfterClass Annotation

This annotation executes a method after all the test methods in the current TestNG class have run. It is best for one-time cleanup after executing all test methods.

import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}

@AfterClass
public void tearDownAfterClass() {
// Code to clean up resources, reset variables, etc.
System.out.println("Cleaning up after all test methods have run.");
}
}

@BeforeGroups Annotation

The @BeforeGroups annotation is used to execute a method before any test method belonging to a specific group runs. This does the setup once before executing any test methods in a specific group run.

import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@BeforeGroups("math")
public void setUpBeforeMathGroup() {
// Code to set up resources, initialize variables, etc. for math group
System.out.println("Setting up before the math group runs.");
}

@Test(groups = "math")
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test(groups = "math")
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}
}

@AfterGroups Annotation

This TestNG annotation invokes a method after all the test methods belonging to a specific group have run. It is useful for a one-time cleanup after executing all test methods in a specific group.

import org.testng.annotations.AfterGroups;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@Test(groups = "math")
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test(groups = "math")
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}

@AfterGroups("math")
public void tearDownAfterMathGroup() {
// Code to clean up resources, reset variables, etc. for math group
System.out.println("Cleaning up after the math group has run.");
}
}

@BeforeSuite Annotation

The @BeforeSuite annotation calls a method before the execution of all tests in a TestNG suite. Hence, use it for one-time setup tasks before running any tests in the suite.

import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@BeforeSuite
public void setUpBeforeSuite() {
// Code to set up resources, initialize variables, etc. before the suite runs
System.out.println("Setting up before the suite runs.");
}

@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}
}

@AfterSuite Annotation

This TestNG annotation calls a method after the execution of all tests in a suite. Hence, it is appropriate to use this for a one-time cleanup after completing all tests in the suite.

import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;
import org.testng.Assert;

public class SimpleTestNGTest {
@Test
public void plusTest() {
int a = 5, b = 3;
int sum = a + b;
Assert.assertEquals(sum, 8);
}

@Test
public void minusTest() {
int a = 5, b = 3;
int difference = a - b;
Assert.assertEquals(difference, 2);
}

@AfterSuite
public void tearDownAfterSuite() {
// Code to clean up resources, reset variables, etc. after the suite runs
System.out.println("Cleaning up after the suite runs.");
}
}

@Factory Annotation

The @Factory annotation in TestNG creates a factory method to generate instances of test classes dynamically. This is useful for running the same tests with different configurations or data.

import org.testng.annotations.Factory;

public class SimpleTestNGFactory {

@Factory
public Object[] createTestInstances() {
return new Object[] { new SimpleTestNGTest(5, 3), new SimpleTestNGTest(2, 2) };
}
}

@Listeners Annotation

@Listeners annotation in TestNG is used to attach listeners to test classes or suites. They can listen for various events during test execution, such as test start, test success, test failure, etc.

import org.testng.annotations.Listeners;

@Listeners(MyTestListener.class)
public class SimpleTestNGTest {
// Test methods
}

If you are planning for a testing Job interview, then you may like to check out the top 25 real-time questions on TestNG.

Must Read – TestNG interview questions

We hope you can use the above information in your TestNG projects. Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy testing,
TechBeamers.

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Chrome Python Shell Extensions The Best 5 Python Shell Chrome Extensions for You
Next Article How to Create TestNG Test Case in Selenium

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x