How to use TestNG annotations in Java?


TestNG is a powerful testing framework, an enhanced version of JUnit which was in use for a long time before TestNG came into existence. NG stands for 'Next Generation'.

TestNG framework provides the following features −

  • Annotations help us organize the tests easily.

  • Flexible test configuration.

  • Test cases can be grouped more easily.

  • Parallelization of tests can be achieved using TestNG.

  • Support for data−driven testing.

  • Inbuilt reporting.

Java 1.5 or higher version allows to interact with TestNG. To run any test or code only in java we must use java main method. TestNG provides us a framework that runs java code without using java main method. Apart from this, better code maintainability, reporting, flexible test configurations are additional advantages of using TestNG along with Selenium.

TestNG Annotation in Java

Annotations were formally added to the Java language in JDK 5 and TestNG made the choice to use annotations to annotate test classes. Following are some of the benefits of using annotations. More about TestNG can be found here

  • TestNG identifies the methods it is interested in by looking up annotations. Hence, method names are not restricted to any pattern or format.

  • We can pass additional parameters to annotations.

  • Annotations are strongly typed, so the compiler will flag any mistakes right away.

  • Test classes no longer need to extend anything (such as TestCase, for JUnit 3).

User can utilize all available TestNG annotations in selenium. Few of those are following:

Sr.No.

                                  Annotation & Description

1

@BeforeSuite

The annotated method will be run only once before all the tests in this suite have run.

2

@AfterSuite

The annotated method will be run only once after all the tests in this suite have run.

3

@BeforeClass

The annotated method will be run only once before the first test method in the current class is invoked.

4

@AfterClass

The annotated method will be run only once after all the test methods in the current class have run.

5

@BeforeTest

The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.

6

@AfterTest

The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.

7

@BeforeGroups

The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.

8

@AfterGroups

The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.

9

@BeforeMethod

The annotated method will be run before each test method.

10

@AfterMethod

The annotated method will be run after each test method.

11

@DataProvider

Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ] where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.

12

@Factory

Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ].

13

@Listeners

Defines listeners on a test class.

14

@Parameters

Describes how to pass parameters to a @Test method.

15

@Test

Marks a class or a method as part of the test.

Let’s ananlyze how to use TestNG annotations in Selenium.

Approach/Algorithm to solve this problem

  • Step 1: Make sure Selenium, TestNG and initial set up of Firefox driver is set up in system properly.

  • Step 2: Create a TestNG class and write selenium code as mentioned in program code.

  • Step 3: Run the TestNGClass file.

Example

The following code to create a TestNG class with Selenium code:

import java.util.concurrent.TimeUnit;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestNGClass {
   WebDriver driver = new FirefoxDriver();
   
   @BeforeTest
   public void launchApp() {
      // Puts an Implicit wait, Will wait for 10 seconds before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      
      // Launch website
      driver.navigate().to("http://www.calculator.net");
      driver.manage().window().maximize();
   }
   
   @Test
   public void calculatePercent() {
      // Click on Math Calculators
      driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
      
      // Click on Percent Calculators
      driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();
      
      // Enter value 10 in the first number of the percent Calculator
      driver.findElement(By.id("cpar1")).sendKeys("10");
      
      // Enter value 50 in the second number of the percent Calculator
      driver.findElement(By.id("cpar2")).sendKeys("50");
      
      // Click Calculate Button
      driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();
      
      // Get the Result Text based on its xpath
      String result =
         driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();
      
      // Print a Log In message to the screen
      System.out.println(" The Result is " + result);
      
      if(result.equals("5")) {
         System.out.println(" The Result is Pass");
      } else {
         System.out.println(" The Result is Fail");
      }
   }
   
   @AfterTest
   public void terminatetest() {
      driver.close();
   }
}

Output

[TestNG] Running:
  C://Users/**************
  The Result is 5
  The Result is Pass
PASSED: calulatePercent
===============================================
Suite1
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
=============================================== 

Updated on: 17-Aug-2023

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements