Mastering TestNG: Exception, Dependency, Parameterization, Multithreading, and Timeout Tests

This guide demonstrates how to use TestNG for exception validation, method dependencies, XML and DataProvider parameterization, multithreaded execution via annotations and XML suites, and timeout enforcement, providing complete Java code examples for each feature.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Mastering TestNG: Exception, Dependency, Parameterization, Multithreading, and Timeout Tests

1. Exception Testing

TestNG allows you to verify that a test method throws a specific exception using the expectedExceptions attribute. When the expected exception occurs, the test passes; otherwise it fails.

package com.huaan.testng;
import org.testng.annotations.Test;
/**
 * Exception testing examples
 */
public class ExpectedExpection {
    @Test(expectedExceptions = RuntimeException.class)
    public void runTimeExpectionFailed(){
        System.out.println("这是我的一个失败的异常测试");
    }

    @Test(expectedExceptions = RuntimeException.class)
    public void runTimeSuccess(){
        System.out.println("这是一个异常测试");
        throw new RuntimeException();
    }
}

2. Dependency Testing

Use dependsOnMethods to specify that a test method should run only after another method succeeds, which is useful for setting up pre‑conditions.

package com.huaan.testng;
import org.testng.annotations.Test;
/**
 * Method dependency example
 */
public class DependTest {
    @Test
    public void test1(){
        System.out.println("test1 run");
        throw new RuntimeException();
    }

    @Test(dependsOnMethods = {"test1"})
    public void test2(){
        System.out.println("test2 run");
    }
}

3. Parameterized Testing

TestNG supports two main ways to feed parameters into test methods.

A. XML‑Based Parameters

Define parameters in an XML suite file and reference them with @Parameters in the test method.

package com.huaan.testng.parameter;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
/**
 * XML parameter example
 */
public class Parameter {
    @Test
    @Parameters({"name","age"})
    public void test1(String name, int age){
        System.out.println("name="+name+"   "+"age="+age);
    }
}

Corresponding parate.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<suite name="parameter">
   <test name="parame">
       <classes>
           <parameter name="name" value="张三"/>
           <parameter name="age" value="30"/>
           <class name="com.huaan.testng.parameter.Parameter"/>
       </classes>
   </test>
</suite>

B. DataProvider Parameterization

Use @DataProvider to supply a matrix of values. The same provider can be shared by multiple test methods, and you can also tailor data per method using the Method argument.

All tests share one data set:

package com.huaan.testng.parameter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
 * DataProvider with a single data set for all tests
 */
public class DataProviderTest {
    @Test(dataProvider = "data")
    public void testDataProvider(String name, int age) {
        System.out.println("name=" + name + ";age=" + age);
    }

    @DataProvider(name = "data")
    public Object[][] providerData() {
        return new Object[][]{
            {"张三", 20},
            {"李四", 30},
            {"王五", 40}
        };
    }
}

Different data per method:

package com.huaan.testng.parameter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
/**
 * DataProvider that returns different data based on the invoking method
 */
public class DataProviderTest {
    @Test(dataProvider = "methodData")
    public void test1(String name, int age) {
        System.out.println("test1----name=" + name + ";age=" + age);
    }

    @Test(dataProvider = "methodData")
    public void test2(String name, int age) {
        System.out.println("test2----name=" + name + ";age=" + age);
    }

    @DataProvider(name = "methodData")
    public Object[][] methodDataTest(Method method) {
        if (method.getName().equals("test1")) {
            return new Object[][]{{"zhangsan", 10}, {"lisi", 20}};
        } else if (method.getName().equals("test2")) {
            return new Object[][]{{"wangwu", 30}, {"zhaoliu", 40}};
        }
        return null;
    }
}

4. Multithreaded Testing

TestNG can run the same test method concurrently using invocationCount and threadPoolSize, or you can configure parallel execution at the suite level via XML.

Annotation‑based concurrency:

package com.huaan.testng.multiThread;
import org.testng.annotations.Test;
/**
 * Run the same test 10 times with a pool of 3 threads
 */
public class MultiTheardOnAnnotion {
    @Test(invocationCount = 10, threadPoolSize = 3)
    public void test(){
        System.out.println(1);
        System.out.printf("Thread Id :%s%n", Thread.currentThread().getId());
    }
}

XML‑based parallelism (methods, classes, or tests):

<?xml version="1.0" encoding="UTF-8" ?>
<!-- Example suite running classes in parallel -->
<suite name="theard" parallel="classs" theards-count="3">
   <test name="demo1">
       <classes>
           <class name="com.huaan.testng.multiThread.MultiTheardOnXML"/>
       </classes>
   </test>
   <test name="demo2">
       <classes>
           <class name="com.huaan.testng.multiThread.MultiTheardOnXML"/>
       </classes>
   </test>
</suite>

Corresponding test class:

package com.huaan.testng.multiThread;
import org.testng.annotations.Test;
/**
 * Simple test methods to be executed in parallel according to the XML suite
 */
public class MultiTheardOnXML {
    @Test
    public void test1(){
        System.out.printf("Thread Id :%s%n", Thread.currentThread().getId());
    }
    @Test
    public void test2(){
        System.out.printf("Thread Id :%s%n", Thread.currentThread().getId());
    }
    @Test
    public void test3(){
        System.out.printf("Thread Id :%s%n", Thread.currentThread().getId());
    }
}

5. Timeout Testing

Use the timeOut attribute to fail a test if it runs longer than the specified number of milliseconds.

package com.huaan.testng;
import org.testng.annotations.Test;
/**
 * Demonstrates TestNG timeout handling
 */
public class TimeOutTest {
    @Test(timeOut = 3000) // 3 seconds
    public void testSuccess() throws InterruptedException {
        Thread.sleep(2000); // finishes within limit
    }

    @Test(timeOut = 2000) // 2 seconds
    public void testFailed() throws InterruptedException {
        Thread.sleep(3000); // exceeds limit, test fails
    }
}

These examples cover the most common TestNG features needed for robust Java unit and integration testing.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javaunit testingmultithreadingTimeoutTestNGparameterized tests
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.