How to Automate TestNG in Selenium

On This Page What is TestNG Framework?What is TestNG in Selenium?

March 21, 2026 · 12 min read · Tool Comparison

How to Automate TestNG in Selenium

TestNG is a popular examination framework for Java that allows users to perform automatize. Selenium, on the other script, is a democratic automation testing tool that enable users to automate web browser. Combining these two tools allows developers to make powerful automated tests for their web applications.

Overview

Goal of TestNG in Selenium

Enable structured, effective, and scalable test automation by compound Selenium ’ s browser automation with TestNG ’ s advanced testing features.

Core Benefits of Using TestNG with Selenium

  • Organize and group test cases for easier direction
  • Execute test in parallel for fast results
  • Enable parameterization for data-driven examination
  • Generate detail HTML reports for best perceptiveness
  • Support cross-browser testing and CI/CD pipelines

Key Features and Achievements

  • Annotations for Structured Execution: @ BeforeSuite, @ AfterSuite, @ BeforeMethod, @ AfterMethod, etc.
  • Parallel & amp; Cross-Browser Support: Run test across multiple browsers and platforms simultaneously
  • Data-Driven Testing:Execute tests with different stimulus sets using @ DataProvider
  • Advanced Reporting: Auto-generated HTML story with execution item and logs
  • Seamless Integration: Works swimmingly with Selenium Grid, CI/CD tools, and BrowserStack base

Business Impact of TestNG in Selenium

  • Faster release cycle with parallel performance
  • High test coverage across browser and environment
  • Improved product quality with structured and validated tests
  • Reduced manual effort through reusable test factor
  • Increased team confidence with honest, repeatable automation

This guide provides a step-by-step tutorial on using TestNG in. Automating TestNG in Selenium affect setting up the environs, creating test causa, configuring TestNG, and integrating Selenium with TestNG.

What is TestNG Framework?

TestNGis an open-source examination automation model for Java. It is developed on the same line as JUnit and NUnit. A few advanced and useful feature provide by TestNG get it a more robust framework than its peers. The NG in TestNG stands for & # 8216; Next Generation. & # 8217;

Created by Cedric Beust, it is used more frequently by developer and testers in test case conception owe to its simplicity of employmultiple annotations, grouping, dependence, prioritization, and parametrization lineament.

What is TestNG in Selenium?

TestNG provides advanced features such as notation, data-driven examination, test sequencing, and parallel testing to help you organize and execute your Selenium tests more efficiently and effectively.

Some of the welfare of utilize TestNG in Selenium:

  • Group test lawsuit into coherent units, making grapple and maintaining your tryout suite easier.
  • Run examination in analogue, significantly reducing the time it takes to execute your test suite.
  • TestNG furnish a across-the-board range of annotations that you can use to customize your tests, such as@ BeforeSuite, @ AfterSuite, @ BeforeTest, @ AfterTest, @ BeforeMethod, and @ AfterMethod.
  • It supports data-driven examination, allow you to run the same test case with multiple trial data sets.
  • Better reporting and logging lineament than early testing fabric make identifying and debugging number in your examination easier.

Hence TestNG framework in Selenium can improve the efficiency and effectuality of your test automation try.

Advantages of TestNG over JUnit

TestNG is a more flexile, powerful, and feature-rich testing framework than, making it a better choice for complex and large examination mechanization labor. Here are the reward of TestNG over JUnit:

  • Flexible examination form and execution options. For example, TestNG allows you to configure exam to run in parallel, run tests in a specific order, and run tryout with different data sets.
  • It supports powerful features such as exam grouping, prioritization, and trial addiction, which are unavailable in JUnit.
  • In TestNG, you can use the DataProvider annotation to pass data to a trial method, while JUnit require you to write custom codification to handle data-driven testing.
  • TestNG generates HTML report with detailed information about test execution, including test results, failure, and errors. JUnit, on the other hand, generates simple text-based study.
  • Supports more advanced annotations such as@ BeforeSuite, @ AfterSuite, @ BeforeTest, @ AfterTest, @ BeforeGroups, @ AfterGroups, @ BeforeClass, and @ AfterClass,which allow you to configure test execution at different levels of graininess.

Follow-Up Read:

Why use TestNG with Selenium?

One of the drawbacks of Selenium is that it do not receive a proper format for the test results. By using the TestNG framework in Selenium, you can:

  • Generate the report in a proper formatting.
  • Include the number of trial suit run; tests passed, failed, and skipped in the study.
  • Group examination cases by converting them to testing.xml
  • Use conjuring reckoning and execute multiple examination without using loop
  • Perform
  • Easily understand annotations

Installing and Setting up TestNG

It ’ s pretty easy to instal TestNG. If you are utilise Eclipse IDE, it comes as a plugin. Below are the measure to install TestNG:

  1. Install Eclipse IDE from theEclipse website. It serves as a platform for you to code on and write your test cases
  2. Once instal, go to help and navigate to the ‘ Eclipse Marketplace ’. The referenced snapshot is below:
  3. Click on ‘ Eclipse Marketplace ’. You will be aim to the mart modal. Type TestNG in the hunt keyword and hit ‘ Go ’. The referenced shot is below:
  4. If TestNG is not instal in your Eclipse, rather than the ‘ Installed ’ push you would see ‘ install ’. Click on install and your TestNG framework will be installed in your Eclipse. As a good practice, Eclipse would urge you to restart to use the characteristic of the installed plugin
  5. Post-restarting your Eclipse, re-verify whether you can see options for creating a TestNG class or not as below:

Also Read:

TestNG Annotations

An note tag provides information about the method, class, and suite. It assist to delineate the execution approach of your test cases and the different lineament associated with it. Below are the major annotations used:

  • @Test& # 8211; This is the root of TestNG test cases. To use TestNG, all method should be annotated with this annotation. Below is an model:

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

@ Test public void setupTestNG () {System.out.println (“ this is a test annotation method ”)}

Must Read:

A few attributes associated with the TestNG annotation are:

  1. Description: You can describe your test case under the description, stating what it does
    @ Test (description= ” This examination validates login functionality ”)
  2. Priority: You can by defining a priority. Based on the defined priority, the trial shall execute in that order.
    @ Test (priority=1)
  3. DependsOnMethod: This property works miracles if one examination lawsuit is dependent on another. For example, to view your profile details, you need to login to the application. So, your profile test case is dependent on the login test causa
    @ Test (dependsOnMethod= ” Login ”)
  4. Enabled: Using this attribute, you can take to execute or skip the execution of this test case. Setting it to true execute it and putting it to false will skip the test from the executing cycle
    @ Test (enabled= ’ true ’)
  5. Groups: Using this attribute, you can club your test cases into a single group and specify the group you wish to action in your TestNG XML file. The test event bludgeon to that group will only be execute, and the rest will be skipped
    @ Test (groups= ” Smoke Suite ”)

While the above ones should help you get started, other major annotation are:

  • @ BeforeMethod and @ AfterMethod& # 8211; These annotations run before and after each examination method
  • @ BeforeClass and @ AfterClass& # 8211; These note run once earlier and after the first @testmethod in a category
  • @ BeforeTest and @ AfterTest& # 8211; The BeforeTest annotation extend before the@ BeforeClassannotation and the AfterTest annotation trial after the@ AfterClassannotation
  • @ BeforeSuite and @ AfterSuite& # 8211; These annotations run before and after any test annotated method in a class respectively. These annotations start the beginning of a tryout and the end of it, for all the classes in a suite

Talking about the execution order of these annotation, they execute in the below order:

@ BeforeSuite - & gt; @ BeforeTest - & gt; @ BeforeClass - & gt; @ BeforeMethod - & gt; @ Test - & gt; @ AfterMethod - & gt; @ AfterClass - & gt; @ AfterCTest - & gt; @ AfterSuite

Note:The key point to remember is apart from@ BeforeMethod and @ AfterMethod, all other annotations run only formerly, whereas the@ BeforeMethod and @ AfterMethodrun billet every@Test method.

How to Write your First TestNG Test

Using the above annotations and attributes, we will publish our first examination case with the TestNG model. Let ’ s take the example of Browserstack, where we will open the landing page and subscribe up on the platform. Let & # 8217; s indite the codification if you understand Selenium and its syntax pretty.

Step # 1 & # 8211;Create your initiative TestNG class by right-clicking on the package and take the & # 8217; Other & # 8217; leaflet from the ‘ New ’ pick.

Step # 2 & # 8211;From the wizard modal, take the TestNG booklet and select the TestNG class as below:

Step # 3 & # 8211;Click the ‘ New ’ push and choose any predefined annotations you like to have in your class as below:

We will useBeforeMethod, AfterMethod, BeforeClass,andAfterClassalong with our test annotation. Do note the XML file name is given on this modal. Using this TestNG XML file, we can choose to define our execution for the defined course or classes.

Step # 4 & # 8211;Click on finish, and you are ready to start writing your first TestNG class. Reference screenshot below, containing the defined methods with the annotations prefer in the step above:

Step # 5 & # 8211;We will automate the sign-up flow using these annotation in the code snippet below.

import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import java.util.concurrent.TimeUnit; importation org.openqa.selenium.By; import org.openqa.selenium.WebDriver; signification org.openqa.selenium.chrome.ChromeDriver; importation org.testng.annotations.AfterClass; public class FirstTestWithTestNGFramework {WebDriver driver; @ BeforeClass world void testSetup () {System.setProperty (`` webdriver.chrome.driver '', `` .\\Driver\\chromedriver.exe ''); driver=new ChromeDriver (); driver.manage () .timeouts () .implicitlyWait (10, TimeUnit.SECONDS); driver.manage () .window () .maximize ();} @ BeforeMethod public void openBrowser () {driver.get (`` https: //www.browserstack.com/ ''); driver.findElement (By.id (`` signupModalButton '')) .click (); System.out.println (`` We are currently on the following URL '' +driver.getCurrentUrl ());} @ Test (description= '' This method validates the signal up functionality '') public void signUp () {driver.findElement (By.id (`` user_full_name '')) .sendKeys (`` user_name ''); driver.findElement (By.id (`` user_email_login '')) .sendKeys (`` email_id ''); driver.findElement (By.id (`` user_password '')) .sendKeys (`` countersign ''); driver.findElement (By.xpath (`` //input [@ name='terms_and_conditions '] '')) .click (); driver.findElement (By.id (`` user_submit '')) .click ();} @ AfterMethod public nothingness postSignUp () {System.out.println (driver.getCurrentUrl ());} @ AfterClass public void afterClass () {driver.quit ();}}

As you can see, in this snippet above, we have used@ BeforeClassannotation to setup the browser.

  • In the @ BeforeMethod, we have opened theBrowserStack homepageand navigated to thesignup page.
  • In the @ Test commentmethod, we are performing the sign-up functionality.
  • In the @ AfterMethod, we are printing the currentURL we are on
  • And in the@ AfterClassmethod, we are closing the browser.

Also, note the associated property ‘ description ’ used with the examination annotation. Now, you must execute this trial and validate your TestNG reports and console output.

Step # 6 & # 8211;To fulfil your report, you can either choose to run directly as a TestNG class or run the XML file created which contains the category gens and details. Below is the auto-created TestNG XML file:

& lt;? XML version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` https: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Suite '' & gt; & lt; test name= '' Test '' & gt; & lt; classes & gt; & lt; class name= '' .FirstTestWithTestNGFramework '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt;! -- Test -- & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;

You can modify the XML file and quotation the various class names when executing multiple classes. You can also define the groups in the XML file you want to fulfil here. Once the modification is done, you can right-click on the file and run it. Your class containing the trial shall be executed. Below is the referenced console yield of the executed test:

Step # 7 & # 8211;To access the TestNG story, you but want to refresh your undertaking folder. A folder as ‘ trial yield ’ will be auto-generated. Within this brochure, you shall see a file ‘ index.html ’ as below:

Step # 8 & # 8211;Double click on it and you can view your TestNG reports, demo the passed and failed methods of the performance as below.

TestNG provides diverse listeners to customize this nonpayment report according to your needs. Learn more about. But this default report will be more than plenty at the beginner level.

Step # 9 & # 8211;As a QA or tester, the next stride is to formalize your trial. If you did not validate your test methods, it basically entail your testing process is uncompleted. To corroborate your exam, TestNG furnish averment for it. So, let us enquire them to complete your TestNG tutorial.

Also Read:

TestNG Assertions

Like JUnit, TestNG render multiple-level assertions to validate your actual upshot against your expected resultant. Few of the commonly used assertions are:

  1. assertTrue& # 8211; This assertion verify whether the defined precondition is true or not. If true, it will pass the test case. If not, it will fail the tryout causa
    Assert.assertTrue (condition);
  2. assertFalse& # 8211; This assertion verify whether the defined stipulation is false or not. If false, it will pass the test event. If not, it will fail the test example
    Assert.assertFalse (precondition);
  3. assertEquals& # 8211; This assertion compares the expected value with the actual value. If both are the same, it passes the test case. If not, it fails the test example. You can compare strings, object, integer values etc. using this assert
    Assert.assertEquals (actual, ask);
  4. assertNotEquals: This is just paired to what assertEquals does. If actual matches the anticipate, the test case fails, else the test case passes
    Assert.assertNotEquals (literal, expected, Message);
Read More:

An important part to notice in assertions is that your tests will not execute to the next line of code if your assertions failed. It will mechanically jump to the future test annotated method.

Now, let us try to validate our code snippet below using assertions. In the snip above, in the@ AfterClassmethod, we will be verifying the current URL we are on and the expected URL, which should be the signup page.

@ AfterMethod public nullity postSignUp () {Assert.assertEquals (driver.getCurrentUrl (), `` https: //www.browserstack.com/users/sign_up '');}

Make this change in your codification snipping above and execute it. The trial causa should pass. Also try yield another expected URL, to validate if the tests fail.

Follow-up Read:

What is Parameterization in TestNG?

Parameterization is a powerful characteristic of TestNG that allows you to write more efficient and effective tests by reusing the same test logic with different input data .. It is useful when you require to test a particular functionality with different input value to ensure that it work correctly in all scenario.

Key Takeaways

TestNG create automated tests more structured, readable, maintainable, and user-friendly. It provides powerful lineament and coverage. Its high-end annotations like dataprovider, make it easier to scale up, as you execute across multiple devices, browsers, and their versions.

  • Do note that BrowserStack back bothescape Selenium tests using TestNG and run Selenium tests utilise JUnit.
  • As an engineering function, if you are automating your test event and considering choosing the right model, start by listing your current demand and usage. A
  • lso, think about what you will need as you scale. Then decide on the framework that act better for you.
  • Avoid picking the latest framework in the market since that might hamper you from scaling down the line.
Tags
42,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free