TestNG - A Comprehensive Guide

https://otieu.com/4/9433883

 TestNG - A Comprehensive Guide

1. Introduction to TestNG

TestNG (Test Next Generation) is an advanced Java testing framework inspired by JUnit and NUnit but with more powerful functionalities. It is widely used for unit testing, functional testing, integration testing, and end-to-end testing.

Why Use TestNG?

  • More powerful annotations than JUnit.
  • Parallel execution of tests.
  • Flexible test configurations with XML.
  • Data-driven testing with @DataProvider.
  • Reporting and logging features.
  • Supports dependent tests, which are not available in JUnit.

2. Installation and Setup

Step 1: Add TestNG to Your Project

For Maven Projects (Add dependency in pom.xml):

xml

<dependency>

    <groupId>org.testng</groupId>

    <artifactId>testng</artifactId>

    <version>7.9.0</version>

    <scope>test</scope>

</dependency>

For Eclipse IDE Users

  1. Go to Help > Eclipse Marketplace.
  2. Search for TestNG and install it.
  3. Restart Eclipse.

3. TestNG Annotations

Annotations in TestNG help define test cases clearly.

Annotation

Description

@Test

Marks a method as a test case.

@BeforeSuite

Runs before the entire test suite.

@AfterSuite

Runs after the entire test suite.

@BeforeTest

Runs before any test methods in a <test> tag in XML.

@AfterTest

Runs after all test methods in a <test> tag in XML.

@BeforeClass

Runs before the first method of the current class.

@AfterClass

Runs after all methods in the current class.

@BeforeMethod

Runs before each test method.

@AfterMethod

Runs after each test method.

@DataProvider

Provides data for data-driven testing.

@Parameters

Used for parameterized testing via XML.


4. Writing a Basic TestNG Test

java

import org.testng.annotations.Test;

 

public class TestExample {

    @Test

    public void testMethod() {

        System.out.println("This is a TestNG test case.");

    }

}

Running the Test

  • In Eclipse: Right-click on the class > Run As > TestNG Test.
  • In IntelliJ IDEA: Right-click on the class > Run 'TestExample'.

5. Advanced TestNG Features

5.1 Grouping Tests

Use groups to categorize and run specific tests.

java

import org.testng.annotations.Test;

 

public class GroupExample {

    @Test(groups = "smoke")

    public void smokeTest() {

        System.out.println("Smoke test executed.");

    }

 

    @Test(groups = {"regression", "sanity"})

    public void regressionTest() {

        System.out.println("Regression & sanity test executed.");

    }

}

Running specific groups from XML:

xml

CopyEdit

<suite name="TestSuite">

    <test name="GroupTest">

        <groups>

            <run>

                <include name="smoke"/>

            </run>

        </groups>

        <classes>

            <class name="GroupExample"/>

        </classes>

    </test>

</suite>


5.2 Data-Driven Testing with @DataProvider

Allows passing multiple sets of data to a single test.

java

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class DataProviderExample {

    @DataProvider(name = "loginData")

    public Object[][] dataProviderMethod() {

        return new Object[][] {{"user1", "pass1"}, {"user2", "pass2"}};

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(String username, String password) {

        System.out.println("Login with: " + username + " and " + password);

    }

}


5.3 Parallel Execution

TestNG can execute tests in parallel to speed up testing.

Parallel execution in testng.xml:

xml

<suite name="ParallelTestSuite" parallel="methods" thread-count="3">

    <test name="ParallelTests">

        <classes>

            <class name="TestClass1"/>

            <class name="TestClass2"/>

        </classes>

    </test>

</suite>


5.4 Dependency Testing

Allows one test to depend on another test.

java

import org.testng.annotations.Test;

 

public class DependencyExample {

    @Test

    public void startApp() {

        System.out.println("Application started.");

    }

 

    @Test(dependsOnMethods = "startApp")

    public void login() {

        System.out.println("User logged in.");

    }

}

5.5 Retry Failed Tests

Automatically retries failed tests using IRetryAnalyzer.

java

import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RetryAnalyzer implements IRetryAnalyzer { private int retryCount = 0; private static final int maxRetryCount = 3; @Override public boolean retry(ITestResult result) { if (retryCount < maxRetryCount) { retryCount++; return true; } return false; } }

Apply to a test:

java

import org.testng.annotations.Test; public class RetryTest { @Test(retryAnalyzer = RetryAnalyzer.class) public void testMethod() { System.out.println("Executing test..."); assert false; // Force failure to see retry } }

6. TestNG Reports & Logs

TestNG generates a detailed HTML report.

Generating Reports

  1. Run your TestNG suite.
  2. Navigate to test-output/index.html for results.

Using Listeners for Custom Reports

java

import org.testng.ITestListener; import org.testng.ITestResult; public class TestListener implements ITestListener { public void onTestSuccess(ITestResult result) { System.out.println("Test Passed: " + result.getName()); } }

Apply to a test class:

java

import org.testng.annotations.Listeners; @Listeners(TestListener.class) public class TestWithListener { @Test public void testMethod() { System.out.println("Executing test..."); } }

7. TestNG vs JUnit

FeatureTestNGJUnit
AnnotationsMore powerfulLimited
Parallel ExecutionYesNo
Grouping TestsYesNo
Dependency TestingYesNo
Data-Driven TestingYesLimited

8. Conclusion

TestNG is a feature-rich testing framework that offers flexibility, efficiency, and powerful test management. Whether you are performing unit tests, functional tests, or integration tests, TestNG provides robust tools to streamline testing in Java.

Would you like additional details on any specific TestNG feature? 🚀

 

https://otieu.com/4/9433883