TestNG Annotations in Selenium WebDriver

TestNG-Annotations-in-Selenium-WebDriver.jpg

Selenium testing software ensures that applications run as expected, delivering quality and reliable software products to the end-users. In the Java domain, several automation testing frameworks like JUnit have been widely used for this purpose. TestNG was developed as an alternative or an advanced upgrade of JUnit that offers enhanced features such as flexible testing, powerful reporting, and most importantly, annotations for simplified test management. The TestNG annotations define how and when methods are executed within your test lifecycle, which makes automation more structured and efficient. In this article, we will learn about TestNG annotations, different types of annotations in Selenium, their order of execution, and much more.

What is Selenium WebDriver?

Selenium WebDriver is an open-source automation testing tool that enables developers to create scripts using programming languages, like Java, Python, C#, etc., for automated control of web browsers and to test web applications. It works as a bridge between your test code and the web browser, allowing you to programmatically control everything a user would typically do when browsing a web page, such as clicking buttons, filling in forms, clicking hyperlinks, and more, allowing you to automate the testing process.

What are TestNG Annotations?

TestNG, also known as Test Next Generation, is an automated testing framework designed to simplify the testing landscape. This platform allows developers to schedule, organize a structure, divide, and execute tests without much manual intervention.

This framework has a feature known as the TestNG annotations. These annotations in the test script dictate which test method will execute next. These annotations are added as a prefix before any test method with the help of @. If there is no “@prefix” added before the method, then in TestNG, such test methods are not run automatically as part of the test script

The @Test is that TestNG annotations that makes a test method visible. This prefix prevents your test method from being ignored in the test script. 

TestNG annotations serve as metadata that provide instructions to the TestNG framework about how to execute your test methods.

Pre-requisites for TestNG in Selenium

Before we can move forward with learning more about TestNG annotations, some prerequisites must be in place for you to successfully run code examples on your local machines.

Software Requirements

  • Java Development Kit (JDK): Version 8 or higher
  • IDE: Eclipse, IntelliJ IDEA, or any Java IDE
  • Selenium WebDriver: Latest stable version
  • TestNG Library: This can be imported or added via Maven dependency or JAR files.

Knowledge Requirements

  • You need to have a basic understanding of Java programming to write and run the code.
  • You should also have a good grasp of the object-oriented programming concepts.
  • You should also be familiar with Selenium WebDriver basics like locating web elements, handling different browsers, and performing basic actions like click() and sendKeys().

Maven Dependency

If you are using Maven, add this dependency to your pom.xml file. A pom.xml file is a configuration file in any Maven project that manages project dependencies, build settings, and external libraries like TestNG and Selenium WebDriver.

<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>

Working of TestNG Annotations

Before we dive into the various types of TestNG annotations that Selenium WebDrivers provide, let us first understand how these annotations dictate the flow of the test scripts.

TestNG annotations work by providing metadata to the TestNG framework about how to execute your testing methods. When TestNG executes your test suite (discussed later), it scans the classes and associated methods looking for annotations so it can create an execution plan in sequence with the TestNG annotations.

A test suite is a collection of multiple test cases or test classes, grouped and executed together as one entity to comprehensively test the different functionalities of an application.

Working of TestNG Annotations

This is how a TestNG annotation will be processed when you run a test script file in the Selenium WebDriver

  1. First, TestNG scans all test classes and finds methods with annotations like @Test, @BeforeClass, @AfterMethod, etc. In this phase, the TestNG framework identifies which ones are the ‘test cases’ and which ones are the methods that set up the environment or clean up after the tests.
  2. After finding the annotated methods, TestNG assembles a plan for the execution of the tests step-by-step in the order of execution according to the TestNG annotations order.
  3. Next, TestNG executes all of the methods in the order in which TestNG assembled them in the previous phase. TestNG executes the annotated methods according to the TestNG annotations sequence to ensure that the tests are set up, executed, and cleaned up correctly.
  4. Once all of the tests are complete, TestNG automatically generates a report in HTML (readable in a browser) that gives the list of tests that passed, failed, or were skipped, execution time for each test, and detailed information about errors if applicable.
Working of TestNG Annotations

This order is essential for ensuring test independence and avoiding interference from separate test methods.

Different Annotations in TestNG

Now, let us discuss the various types of TestNG annotations in Selenium WebDriver. Each annotation serves different purposes in the test lifecycle, and below, they are explained in detail.

Different types of TestNG Annotations

1. @BeforeSuite

The @BeforeSuite annotation runs only once before all tests execute in a test suite. This is the first method to execute in the entire TestNG annotations order. You should use this annotation for the following cases: 

  • Environment preparation: Since for the whole project the environment is set only once, you can use this annotation to prepare the testing environment by creating test folders, clearing log files, or setting up test servers
  • Database connections: Database connection is also something you need to establish only once, so this annotation is perfect.
  • Global configuration setup: This is similar to generating an HTML report, taking final screenshots, or saving test execution logs related to that test group.
  • Loading property files: This is like deleting test user accounts created in the test, removing test records created in the database, or clearing uploaded test files from the server.
Java

2. @BeforeTest

The @BeforeTest annotation is a TestNG annotations that executes before each <test> tag in the TestNG XML file. This annotation can be used for tasks that include browser initialization, test-specific configuration, setting up test data, and configuring test parameters.

You can think of @BeforeTest as preparing your study notes before you start a subject. You get the right textbook, notes, and tools ready for that specific subject, even though you might study multiple topics in one day.

Java

3. @BeforeClass

The @BeforeClass annotation runs once before the first test method in the current class. 

This works best for: 

  • Class-level setup: Preparing things for all test methods in that particular class, such as logging into an application or the ability to navigate to a specific part of the application.
  • Instantiating objects: Creating any objects, such as page objects (LoginPage, HomePage), that will be used by multiple test methods in the class to interact with the web elements.
  • Setting up class variables: Initializing class variables that will hold any important information (such as user data or configuration settings) that will be used by all tests in the class.
  • Preparing test fixtures: Setting up the basic test environment or data that will be fundamental for all test methods in the class, such as creating a test user account or setting up some sample data.
Java

4. @Test

The @Test annotation is the main TestNG annotations that marks a method as a test case. Before, all the annotations could be considered as “preparation for test” annotations. These TestNG annotations are actually the annotations that will mark the actual test to be performed. The @Test annotation supports many different parameters that help you control how tests run:

  • priority: This will execute tests in a specific order using numbers (smaller numbers execute first). For example @Test(priority = 1) will execute before @Test(priority = 2).
  • enabled: This is a way to control whether tests are turned on or off without deleting the code. Set enabled = false to skip a test. For example, @Test(enabled = false).
  • dependsOnMethods: This will allow you to group tests together, so you can run certain groups together. For example, @Test(groups = “smoke”) or @Test(groups = {“smoke”, “regression”}).
  • groups: This organizes tests into categories so you can run specific groups together. Example: @Test(groups = “smoke”) or @Test(groups = {“smoke”, “regression”}).
  • description: This will add a meaningful description for your test and will be displayed in your reporting. For example, @Test(description = “Verify user can log in with valid credentials”).
  • timeout: The timeout parameter sets a maximum time limit for the test in milliseconds. Example: @Test(timeout = 5000) fails the test if it takes longer than 5 seconds.
  • expectedExceptions: This expects the test to throw a specific exception. Example: @Test(expectedExceptions = IllegalArgumentException.class).

How to pass parameters:

You can pass the parameters in the following manner: 

Java

5. @AfterClass

The @AfterClass annotation executes once after all test methods in the current class have been executed. As the name suggests, it is used after the test is executed; therefore, it is good for the following scenarios:

  • Class-level cleanup: This situation would take this annotation as it will be cleaning up things that you set up for the whole class, like logging out of the application, or closing the database connections that all the tests in the class were using.
  • Releasing resources: Situations where releasing memory and system resources is done by closing files, network connections, or other resources that were opened during class setup, to prevent memory leaks.
  • Clearing variables: In addition, the other class-level variables and objects will be reset or nullified (these can be page objects or data arrays, for example) so they will not accidentally interfere with other test classes.
  • Cleanup operations: Lastly, the final cleanup actions include deletion of temporary test files, clearing away test data left behind in databases, or resetting the state of the application back to the original state.
Java

6. @AfterTest

The @AfterTest annotation runs after each <test> tag in the TestNG XML file completes. This is useful for:

  • Test-specific cleanup: Like clearing browser cookies, deleting temporary files created during the test, or resetting application settings that were changed for that specific test group.
  • Closing browser instances: For instance, calling driver.quit() means to fully close the browser window and close and quit the WebDriver session for that instance of memory to be released from the system.
  • Generating test reports: For instance, creating HTML reports, taking final screenshots, or saving test execution logs for the specific test run.
  • Clearing test data: For instance, if you created test user accounts, delete those, clean the test data created in the database, and delete the uploaded test files from the server.
Java

7. @AfterSuite 

The @AfterSuite annotation is the last method to execute in the entire test suite. This annotation is perfect for:

  • Final cleanup operations: Just like cleaning up temporary test directories, clearing system cache, or removing any leftover test files created during the entire testing process.
  • Closing database connections: Calling connection.close() to disconnect from test databases, data sources, or any external systems utilized during the test process.
  • Generating final reports: Just like creating a master HTML report of all tests or sending email notifications with the test summary, or uploading the reports to a shared place.
  • Environment teardown: Just like shutting down test servers, shutting down background processes, resetting the configuration of systems, or cleaning up any actions taken in the environment by the tester.
Java

8. @DataProvider

The @DataProvider annotation provides data to test methods. This feature provides datasets in a data-driven manner by allowing multiple datasets as test data. It also supports Object[][] return type, and can also be a type of Iterator. Ultimately, this allows us to create parameterized testing in test scripts.

Java

9. @BeforeMethod and @AfterMethod

The @BeforeMethod and @AfterMethod annotations run before and after each test method, respectively:

  • @BeforeMethod: Before each @Test method is helpful for method-level setups, resetting the application state, clearing all previous browser cache, or preparing new test data.
  • On the other hand, @AfterMethod runs after each @Test method to perform tasks like method-level cleanup, taking screenshots, logging test results, or resetting variables.
Java

TestNG Annotations Order of Execution

TestNG Annotations Order of Execution

As depicted in the picture above, the order of execution of TestNG annotations is easy to understand because of the “before” and “after” keywords. To simplify it even more, below is a simple study schedule analogy to help you remember the order of execution. Imagine preparing for and finishing different subjects in a study schedule:

  1. @BeforeSuite – Like setting up your entire study room before starting any subjects.
  2. @BeforeTest – Like getting ready for a particular subject’s study session (e.g., bringing out all math books).
  3. @BeforeClass – Like arranging everything you need for one specific topic in that subject.
  4. @BeforeMethod – Like sharpening your pencil or opening your notebook before solving each problem.
  5. @Test – Solving the problem or answering the question.
  6. @AfterMethod – Like putting down your pencil and closing your notebook right after solving one problem.
  7. @AfterClass – Like cleaning up your study desk after finishing all problems for that topic (your example).
  8. @AfterTest – Like putting away all materials for that subject when you’re done with the session.
  9. @AfterSuite – Like locking up your study room once all subjects are completed.

This TestNG annotations sequence ensures that your tests run in a predictable and organized manner, making debugging easier and test results more reliable.

Advantages of TestNG over JUnit

We know that TestNG was developed as an upgraded version of JUnit, but let us closely look at the advantages that TestNG has over the JUnit testing framework and why it is a preferred choice for annotations in Selenium:

Feature TestNG JUnit
Annotations Support Rich set of annotations (@BeforeSuite, @AfterSuite, etc.) Limited annotations
Test Dependencies Supports method dependencies No dependency support
Grouping Advanced test grouping capabilities Basic grouping
Data Providers Built-in data provider support Requires external libraries
Parallel Testing Native parallel execution Limited parallel support
Test Configuration XML-based configuration Annotation-based only
Reporting Advanced HTML reports Basic reporting
Exception Handling Better exception handling Limited exception handling
Test Prioritization Built-in priority support No priority support
Flexible Setup Multiple setup/teardown levels Limited setup options

Real World Example of TestNG Annotations in Selenium

Let’s create a practical example that demonstrates all TestNG annotations in action with Selenium WebDriver:

Project Structure for TestNG Annotations Example

Step 1: Create Test Class Structure

Java

Step 2: Create TestNG XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<suite name="TestNG Annotations Suite">
    <test name="Annotation Test">
        <classes>
            <class name="TestNGAnnotationsExample"/>
        </classes>
    </test>
</suite>

Step 3: Create a pom.xml File

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ContentProject</groupId>
  <artifactId>ContentProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
        <!-- Selenium Java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.23.0</version>
        </dependency>

        <!-- TestNG -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.10.2</version>
            <scope>test</scope>
        </dependency>

        <!-- WebDriver Manager -->
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>5.8.0</version>
        </dependency>
    </dependencies>
</project>

Step 4: Expected Output

When you run this example, the output will follow the TestNG annotations order:

TestNG Annotations in Selenium - Output

Explanation: This code example demonstrates the complete TestNG annotations sequence and shows how each annotation serves a specific purpose in the actual test lifecycle.

Conclusion

When it comes to structured, maintainable, efficient test automation, TestNG annotations are important. If you want to properly set up tests, execute them, and clean up in the end with Selenium, then understand TestNG annotations and how they work. Each of the annotations has a specific role to play during a test run, and this article briefly explains its key features, such as @DataProvider, which can offer you strong, data-driven automation testing capabilities. Compared to JUnit, TestNG gives you enterprise flexibility and control, thus making it an ideal automation framework for enterprise-level automation. Understanding the annotation sequence allows you to avoid common testing pitfalls that can result in inconsistent or unreliable results. With enough practice, these annotations will become second nature to you, and you will be able to design scalable, reliable testing frameworks that meet your project’s complex needs efficiently.

Prepare for your interview with our extensive Automation Testing Interview Questions and Answers blog.

TestNG Annotations in Selenium WebDriver – FAQs

Q1. What are TestNG annotations in Selenium?

TestNG annotations in Selenium are special markers that define the execution order and behavior of test methods, enabling better control over test setup, execution, and teardown.

Q2. How many TestNG annotations are available in Selenium?

TestNG provides several annotations in Selenium, such as @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, @Test, @AfterMethod, @AfterClass, @AfterTest, and @AfterSuite.

Q3. What is the difference between @BeforeTest and @BeforeSuite in TestNG annotations?

@BeforeSuite runs once before all tests in the entire suite, while @BeforeTest runs before the first test method within a tag in the TestNG XML configuration.

Q4. How to use the @Test annotation in TestNG for Selenium automation?

In TestNG annotations, @Test marks a method as a test case. This method can include Selenium WebDriver code to perform automated browser interactions and validations.

Q5. What is the difference between @AfterClass and @AfterTest in TestNG annotations?

In TestNG annotations, @AfterClass runs after all test methods in the current class have executed, whereas @AfterTest runs after all test methods within a tag have completed.

About the Author

Lead Technical Research Analyst - Automation, Simplilearn

Naseeha specialises in automation testing and has more than 4+ years of hands-on experience in the automation domain. She is an avid writer who hones her technical writing skills in her free time. She has also trained over 1000+ professionals in Java, Selenium, and other automation frameworks.

EPGC Cloud