The Wayback Machine - https://web.archive.org/web/20241118063032/https://www.geeksforgeeks.org/unit-testing-integration-testing-priority-testing-using-testng-in-java/
Open In App

Unit Testing, Integration Testing, Priority Testing using TestNG in Java

Last Updated : 15 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

TestNG is an automated testing framework. In this tutorial, let us explore more about how it can be used in a software lifecycle. 

Unit Testing

Instead of testing the whole program, testing the code at the class level, method level, etc., is called Unit Testing The code has to be split into separate classes and methods so that testing can be carried out easily at a unit level.

Integration Testing

After the completion of Unit testing, there will always be the necessity for integration testing. Several units are tested in groups and this will help to reduce the defects exposed at the time of integration of several modules.

Example: We can run tests together by means of specifying “suite name” and can do different classes together.

Priority Testing

By using annotations like @Test(priority=1/2/…), we can set the priority of the tests. If a test class is having @Test annotation alone, it will high priority and if any specific test numbers are given, it is executed as per the order. So we can set the order of execution by using annotations as above. Let us take a maven project and from there will cover important topics.

Example Project

Project Structure:

Project Structure

 

This is a maven kind of project and hence dependencies need to be mentioned in 

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
    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>com.gfg.testng</groupId>
        <artifactId>testng</artifactId>
        <version>0.1.0-SNAPSHOT</version>  
      
    <name>testng</name>
    <packaging>jar</packaging> 
    <dependencies>
      <!-- This is the essential dependency required for testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </dependency>
      <!-- As we are logging, below dependency is required -->
        <dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-api</artifactId>
 <version>1.7.9</version>
</dependency>
    </dependencies>
  
    <build>
        <finalName>testng</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
    </build>
  
    <profiles>
        <profile>
            <id>default-second</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <suiteXmlFiles>
                                <suiteXmlFile>src\test\resources\parametrized_testng.xml</suiteXmlFile>
  
                            </suiteXmlFiles>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>integration-lite-second</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <suiteXmlFiles>
                                <suiteXmlFile>src\test\resources\test_int.xml</suiteXmlFile>
                            </suiteXmlFiles>
                        </configuration>
                    </plugin>                  
                      
                </plugins>
            </build>
        </profile>
    </profiles>
  
    <properties>
        <testng.version>7.1.0</testng.version>
                <!-- https://maven.apache.org/general.html#encoding-warning -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
  
    </properties>
  
</project>


In TestNG, Via XML files, We can pass parameters as specified in the below XML using <parameter> tag with name and value

XML




<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="My test suite">
<listeners>
<listener class-name="com.gfg.reports.CustomisedListener"></listener>
</listeners>
    <test name="numbersXML">
        <!-- We can specify as much parameters and their values here -->
        <parameter name="value" value="1"/>
        <parameter name="isEven" value="false"/>
        <classes>
            <class name="com.gfg.ParametrizedUnitTest"/>
        </classes>
    </test>
</suite>


These parameters are collected via @DataProvider or @Parameter in Java files

@DataProvider(name = "numbers")
public static Object[][] evenNumbers() {
        return new Object[][]{{11, false}, {2222, true}, {4882, true}};
    }

We can run tests together by means of specifying “suite name” and can do different classes together.

XML




<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="int">
    <test name="integration tests">
        <classes>
            <class name="com.gfg.MultiThreadedIntegrationTest" />
            <class name="com.gfg.TimeOutCheckTest" />
        </classes>
    </test>
</suite>


This specifies that “int” is the suite name and 2 classes namely com.gfg.MultiThreadedIntegrationTest and com.gfg.TimeOutCheckTest together. Like this, we can group classes under a single suite. And also we can specify different suite names and can group classes whichever we need. Dependency tests. i.e. depends upon a specific test and thereupon logging some information

Usecase: Check whether an email is valid or not and if valid, proceed to the next set of steps

private String userEmail = "geek@gfg.com";

@Test
public void checkForValidMail() {
    boolean validEmail = userEmail.contains("@");
    Assert.assertEquals(validEmail, true);
}


// If first test is success, below test executes and logs the information
@Test(dependsOnMethods = {"checkForValidMail"})
public void logInWhenEmailValid() {
   LOGGER.info("Given Email {} valid >> and logging in", userEmail);
}

Order of test execution can be controlled by using @Priority annotation

@Test(priority = 1) // This is executed first
public void stringToIntCheck() {
        String testString = "100";
        assertTrue(Integer.valueOf(testString) instanceof Integer);
    }

@Test(priority = 2) // This is second
public void intToStringCheck() {
        int testInt = 100;
        assertTrue(String.valueOf(testInt) instanceof String);
    }

Test Timeout can be mentioned by using @Test(timeout=<certain value>). TestNG supports for timed out tests. 

@Test(timeOut = 1000, enabled = false)
public void asNoStoppingPointItRunsTimeOut() {
     while (true) ;
}
  • Actually, in the previous test, we are having enabled = false,, that is if we want to ignore the test cases
  • We can include 
    • @BeforeClass and @AfterClass at the class level are mainly used to initialize and clean up the code. 
    • Similarly, we can include @BeforeMethod and @AfterMethod at the method level
    • @BeforeSuite, @AfterSuite, @BeforeGroup, and @AfterGroup annotations, for configurations at suite and group levels respectively.
 private int evenNumber, oddNumber;

    @BeforeClass
    public void setup() {
        evenNumber = 100;
        oddNumber = 59;
    }

    @AfterClass
    public void tearDown() {
        evenNumber = 0;
        oddNumber = 0;
    }

As a whole let us see the java code with the above features

DependencyUnitTest.java

Java




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
  
public class DependencyUnitTest {
  
    private static final Logger LOGGER = LoggerFactory.getLogger(DependencyUnitTest.class);
  
    private String userEmail = "geek@gfg.com";
  
    @Test
    public void checkForValidMail() {
        boolean validEmail = userEmail.contains("@");
        Assert.assertEquals(validEmail, true);
    }
  
    @Test(dependsOnMethods = {"checkForValidMail"})
    public void logInWhenEmailValid() {
        LOGGER.info("Given Email {} valid >> and logging in", userEmail);
    }
}


MultiThreadedIntegrationTest.java

Java




import org.testng.Assert;
import org.testng.annotations.Test;
  
public class MultiThreadedIntegrationTest {
  
    @Test(threadPoolSize = 5, invocationCount = 10, timeOut = 1000)
    public void checkForCount() {
        int count = Thread.activeCount();
        Assert.assertTrue(count > 2);
    }
  
}


OddOrEvenNumberCheck.java

Java




import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
  
public class OddOrEvenNumberCheck extends TestNG {
    
    private int evenNumber, oddNumber;
  
    @BeforeClass
    public void setup() {
        evenNumber = 100;
        oddNumber = 59;
    }
  
    @AfterClass
    public void tearDown() {
        evenNumber = 0;
        oddNumber = 0;
    }
  
    @Test
    public void checkEven() {
        Assert.assertTrue(evenNumber % 2 == 0);
    }
    @Test
    public void checkOdd() {
        Assert.assertTrue(oddNumber % 2 == 1);
    }
  
}


ParametrizedUnitTest.java

Java




import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
  
import static org.testng.Assert.assertEquals;
  
public class ParametrizedUnitTest {
  
    @DataProvider(name = "numbers")
    public static Object[][] evenNumbers() {
        return new Object[][]{{11, false}, {2222, true}, {4882, true}};
    }
  
    @Test(dataProvider = "numbers")
    public void evenNumberCheck(Integer number, boolean expected) {
        assertEquals(expected, number % 2 == 0);
    }
  
    @Test(dataProvider = "numbersObject")
    public void evenNumberObjectCheck(EvenNumberPOJO number) {
        assertEquals(number.isEven(), number.getValue() % 2 == 0);
    }
  
    @DataProvider(name = "numbersObject")
    public Object[][] parameterProvider() {
        return new Object[][]{{new EvenNumberPOJO(111, false)}, {new EvenNumberPOJO(2432, true)}, {new EvenNumberPOJO(4712, true),}};
    }
  
    class EvenNumberPOJO {
        private int value;
        private boolean isEven;
  
        EvenNumberPOJO(int number, boolean isEven) {
            this.value = number;
            this.isEven = isEven;
        }
  
        int getValue() {
            return value;
        }
  
        public void setValue(int value) {
            this.value = value;
        }
  
        boolean isEven() {
            return isEven;
        }
  
        public void setEven(boolean even) {
            isEven = even;
        }
  
        @Override
        public String toString() {
            return "EvenNumber{" +
              "value=" + value +
              ", isEven=" + isEven +
              '}';
        }
    }
}


PriorityUnitTest.java

Java




import org.testng.annotations.Test;
import static org.testng.Assert.assertTrue;
  
public class PriorityUnitTest {
  
    @Test(priority = 1)
    public void stringToIntCheck() {
        String testString = "100";
        assertTrue(Integer.valueOf(testString) instanceof Integer);
    }
  
    @Test(priority = 2)
    public void intToStringCheck() {
        int testInt = 100;
        assertTrue(String.valueOf(testInt) instanceof String);
    }
  
}


TimeOutCheckTest.java

Java




import org.testng.annotations.Test;
  
public class TimeOutCheckTest {
    // @Test(timeOut = 1000)
    // If we want to skip the test means, 
    // enabled = false has to be added
    @Test(timeOut = 1000, enabled = false)
    public void asNoStoppingPointItRunsTimeOut() {
        while (true) ;
    }
}


Now let’s run the test by using

mvn test

Or from eclipse 

Output:

 

We can see the success/failure reports under the target/surefire-reports folder as well.



Previous Article
Next Article

Similar Reads

How to create TestNG XML file and Execute TestNG.XML File?
TestNG is a powerful testing framework for Java developers, inspired by JUnit and NUnit. It supports a wide range of testing needs, from unit testing to integration testing. One of the key features of TestNG is the ability to control the execution of tests using an XML file, known as the TestNG XML file. This file defines which classes and methods
4 min read
How to execute TestNG and Maven without testng.xml file?
To run TestNG tests with Maven, it is not mandatory to configure any testng.xml. Instead of this you just let Maven do the execution with maven-surefire-plugin of the Maven build lifecycle and for that you don't need to define any test suite, classes, or methods in testng.xml. The maven-surefire-plugin allows you to run your TestNG tests directly b
2 min read
What is the order of test execution with priority in TestNG?
In TestNG, controlling the order of test execution is crucial for ensuring that your tests run in a logical sequence, especially when certain tests depend on others. The priority attribute in TestNG allows developers to define the order of execution explicitly. A lower priority value means the test will execute earlier, while a higher value will pu
4 min read
How to disable an entire unit test in TestNG?
TestNG is an integrated testing framework for Java, which provides several features to support automated testing. As with most test management solutions, a clear need has been seen to be able to comment out selected unit tests so that the code containing them is not removed entirely. In this article, I’ll explain to you how you can deactivate an en
5 min read
Difference Between Unit, Functional, Acceptance, and Integration Tests
Here, we will discuss the differences between unit testing, functional testing, acceptance testing, and integration testing. Unit Testing It is a testing technique wherein the simple or smallest units of a software program are examined personally for bugs and errors. These smallest units may be examined independently and personally as they do now n
7 min read
Severity in Testing vs Priority in Testing
In software testing, a bug is the most critical entity. The most important attributes that can be assigned to a bug are priority and severity. They help teams to efficiently fix bugs and go through the release scheduling processes without letting any critical issues fall through the gaps. The article focuses on discussing the difference between Sev
6 min read
How to exclude a test class from a testing suite using testng.xml?
In TestNG, managing which test classes or methods to include or exclude in your test suite is straightforward using the testng.xml configuration file. Excluding a test class can be particularly helpful when you want to skip certain tests during specific runs, like regression testing or temporarily ignoring tests still in development. Approach to Ex
2 min read
Integration Testing Tool - Software Testing
Integration Testing Tools are essential in the software development lifecycle, designed to streamline the process of testing how different components of an application work together. Unlike unit testing, which focuses on individual components, integration testing ensures that multiple modules or services interact as intended. These tools facilitate
9 min read
Data Driven Testing With TestNG
Data-Driven Testing with TestNG is a powerful approach that allows you to run the same test case with multiple sets of data. This methodology helps in achieving comprehensive test coverage and ensures that your application works correctly with various input values. By using external data sources like Excel or CSV files, you can easily manage and ma
4 min read
How to Test Java Application using TestNG?
TestNG is an automation testing framework widely getting used across many projects. NG means “Next Generation” and it is influenced by JUnit and it follows the annotations (@). End-to-end testing is easily handled by TestNG. As a sample, let us see the testing as well as the necessity to do it via a maven project. Sample Maven Project Project Struc
4 min read
Software Testing - Unit Testing Tools
Unit Testing is a part of software testing where testing is performed on isolated small parts of the code. The objective of Unit Testing is to isolate small portions of application code that could be individually tested and verified, provided all the isolated code units have been developed in the correct procedure. It is performed by the developmen
8 min read
Difference between Unit Testing and System Testing
Unit testing involves testing individual components of software in isolation to ensure they function correctly, primarily by developers using automated test frameworks. It focuses on early bug detection and code quality improvement. On the other hand, system testing checks the integrated software system as a whole, validating its functionality agai
4 min read
Unit Testing - Software Testing
Unit Testing is a software testing technique in which individual units or components of a software application are tested in isolation. These units are the smallest pieces of code, typically functions or methods, ensuring they perform as expected. Unit testing helps in identifying bugs early in the development cycle, enhancing code quality, and red
11 min read
Advantages of using TestNG with Cucumber
If you are working in the sphere of software testing, you probably heard about Cucumber and TestNG – these tools are often used in combination to reach high effectiveness and maintainability of the tests. Cucumber is one of the most popular tools for behaviour-driven development (BDD) that allows expressing tests in a simple language comprehensible
4 min read
Big Bang Integration Testing
Integration testing is a type of testing that is used to check the functionality of integrated components of a software system. It is usually performed after unit testing and before validation testing. In integration testing, individual software components are combined and tested as a group. The purpose of this testing is to check if the components
8 min read
Continuous Integration and Continuous Testing: The Dynamic Duo
CI and CT are mandatory and widely used practices in modern software development that aim to increase productivity, code quality, and software reliability. This article elaborates on these practices, their processes, and related methodologies. Table of Content Understanding Continuous Integration (CI)Understanding Continuous Testing (CT)Implementat
5 min read
Integration Testing - Software Engineering
Integration testing is the process of testing the interface between two software units or modules. It focuses on determining the correctness of the interface. The purpose of integration testing is to expose faults in the interaction between integrated units. Once all the modules have been unit-tested, integration testing is performed. Table of Cont
11 min read
Unit Testing in Spring Boot Project using Mockito and Junit
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
6 min read
How to Use Hard Asserts in TestNG?
TestNG is an open source automation framework that is used to perform software testing more easily, it provides various annotations and is used to perform parallel testing and produce the test reports. What are Asserts? To check whether the test failed or passed during the testing, the TestNG provides an Assert method in which we can compare the Ac
2 min read
How to use Regex in TestNG?
In this article, we will see how to use Regex in TestNG. In TestNG, we can use Regular Expressions for two purposes: To Include Test CasesTo Exclude Test Cases To include test cases we use the include the keyword in the testng.xml configuration file.To Exclude test cases we use the exclude keyword in the testng.xml configuration file.Table of Conte
5 min read
TestNG @AfterClass Annotations
The Concept Annotations is introduced in Java 1.5 (jdk5). The Popular Annotation in Java is @override. We use the same annotation concept in TestNG. In TestNG, there are 10 Annotations @BeforeSuite@AfterSuite@BeforeTest@AfterTest@BeforeClass@AfterClass@BeforeMethod@AfterMethod@BeforeGroups@AfterGroupsIn this article, we will learn about @AfterClass
3 min read
TestNG @BeforeClass Annotations
The Concept Annotations is introduced in Java 1.5 (jdk5). The Popular Annotation in Java is @override. We use the same annotation concept in TestNG. In TestNG, there are 10 Annotations @BeforeSuite@AfterSuite@BeforeTest@AfterTest@BeforeClass@AfterClass@BeforeMethod@AfterMethod@BeforeGroups@AfterGroupsIn this article, we will learn about @BeforeClas
3 min read
TestNG @BeforeMethod Annotations
The Concept Annotations is introduced in Java 1.5. The Popular Annotation in Java is @override. We use the same annotation concept in TestNG. In TestNG, there are 10 Annotations: @BeforeSuite@AfterSuite@BeforeTest@AfterTest@BeforeClass@AfterClass@BeforeMethod@AfterMethod@BeforeGroups@AfterGroupsIn this article, we will learn about @BeforeMethod. Wh
4 min read
TestNG @AfterMethod Annotations
The Concept Annotations is introduced in Java 1.5. The Popular Annotation in Java is @override. We use the same annotation concept in TestNG. In TestNG, there are 10 Annotations: @BeforeSuite@AfterSuite@BeforeTest@AfterTest@BeforeClass@AfterClass@BeforeMethod@AfterMethod@BeforeGroups@AfterGroupsIn this article, we will learn about @AfterMethod. Wha
3 min read
TestNG @BeforeGroups Annotations
The Concept Annotations is introduced in Java 1.5 (jdk5). The Popular Annotation in Java is @override. We use the same annotation concept in TestNG. In TestNG, there are 10 Annotations @BeforeSuite@AfterSuite@BeforeTest@AfterTest@BeforeClass@AfterClass@BeforeMethod@AfterMethod@BeforeGroups@AfterGroupsIn this article, we will learn about @BeforeGrou
2 min read
How to Create Test Suite in TestNG?
In this article we will learn about test suites and how can we build them using Java and TestNG. TestNG is a modern testing framework that is used very widely used today. It has a broad base of features that allow us to write unit tests and club them together in groups. Table of Content What is a Test Suite?Steps to Create Test Suite in TestNGUnder
11 min read
Difference between BeforeTest and BeforeMethod in TestNG
TestNG Framework is an open-source test automation framework based on JUnit and NUnit. It is considered an improved version of these two frameworks since it adds new features such as test annotations, test prioritization in TestNG, and grouping, parameterization, and sequencing techniques in the code that were not before feasible. The Concept Annot
7 min read
How to Use DataProvider in TestNG Selenium?
DataProvider in TestNG is a powerful feature that facilitates data-driven testing in Selenium. It allows you to run the same test method multiple times with different sets of data, enhancing test coverage and efficiency. By using DataProvider, you can easily parameterize your tests and ensure that your web application is robust across various data
5 min read
Difference between Selenium and TestNG
Selenium and TestNG are two powerful tools widely used in the field of software testing. Selenium is an open-source toolset specifically designed for automating web browsers, enabling testers to write scripts in various programming languages like Java, C#, Python, and Ruby. It supports multiple browsers, including Chrome, Firefox, Safari, and Edge,
5 min read
How to Download the Latest TestNG Jar File?
TestNG is a widely used testing framework in Java that helps you organize and run your tests efficiently. Whether you're a developer or a tester, keeping TestNG up to date ensures you have access to the latest features and improvements. You'll need to download the latest TestNG jar file to get started or update your project. This guide will show yo
2 min read
three90RightbarBannerImg