October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Use TestNG DataProviders with Examples

A practical TestNG DataProvider guide with Java examples for row-based inputs, reusable providers, method-aware data, parallel execution, and common configuration issues.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a TestNG @DataProvider method to supply multiple argument sets to one @Test method. Each row of the provider’s returned data becomes a separate test invocation, and the values in that row are passed to the test method’s parameters in order.

How a TestNG DataProvider works

A provider is a method annotated with @DataProvider. A test connects to it by naming it in @Test(dataProvider = "..."). In the basic form shown in the TestNG documentation, the provider returns an Object[][]: each inner array is one invocation’s arguments.

For example, the first row below calls the test with "alice" and "correct-horse"; the second row calls it with "bob" and "battery-staple". The test method’s parameter count and types should match the values supplied by each row.

Basic example

Place the provider and test in the same class when the data is specific to that test or class:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class LoginTest {
    @DataProvider(name = "credentials")
    public Object[][] credentials() {
        return new Object[][] {
            {"alice", "correct-horse"},
            {"bob", "battery-staple"}
        };
    }

    @Test(dataProvider = "credentials")
    public void loginAcceptsCredentials(String username, String password) {
        // Exercise the behavior under test here.
    }
}

This example illustrates the TestNG mechanism; it does not implement a login operation or make an assertion. Replace the comment with the behavior and assertions your test needs. The example uses Object[][], a documented form, not a claim that it is the only return form accepted by every TestNG version.

Put reusable data in another class

To share a provider across test classes, specify its class with dataProviderClass. The TestNG documentation says the provider method in that specified class needs to be static.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import org.testng.annotations.DataProvider;

public class CommonTestData {
    @DataProvider(name = "credentials")
    public static Object[][] credentials() {
        return new Object[][] {
            {"alice", "correct-horse"},
            {"bob", "battery-staple"}
        };
    }
}
import org.testng.annotations.Test;

public class LoginTest {
    @Test(dataProvider = "credentials", dataProviderClass = CommonTestData.class)
    public void loginAcceptsCredentials(String username, String password) {
        // Exercise the behavior under test here.
    }
}

Without dataProviderClass, TestNG looks for the named provider in the test class or a base class. Keeping a provider close to one consumer makes its purpose easy to see; placing it in a separate class can reduce duplication when multiple tests genuinely need the same inputs.

Reuse one provider for different test methods

A provider may accept java.lang.reflect.Method. TestNG supplies the method that is about to receive data, so the provider can select rows based on the requesting test method. This is useful when a shared provider serves tests that need different inputs; keep the selection logic explicit so a change to a test method name does not silently select the wrong data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class SharedDataTest {
    @DataProvider(name = "cases")
    public Object[][] cases(Method testMethod) {
        if (testMethod.getName().equals("acceptsValidInput")) {
            return new Object[][] {{"valid"}};
        }
        if (testMethod.getName().equals("rejectsInvalidInput")) {
            return new Object[][] {{"invalid"}};
        }
        throw new IllegalArgumentException(
            "No data configured for " + testMethod.getName());
    }

    @Test(dataProvider = "cases")
    public void acceptsValidInput(String input) {
        // Assert the valid-input behavior.
    }

    @Test(dataProvider = "cases")
    public void rejectsInvalidInput(String input) {
        // Assert the invalid-input behavior.
    }
}

The explicit exception makes an unhandled consumer visible instead of returning an accidental empty or inappropriate data set. Adapt the conditions and values to the cases your tests actually cover.

Run data-driven invocations in parallel

Parallel execution is opt-in on the provider: set parallel = true on @DataProvider. The TestNG documentation describes a default data-provider pool size of 10 for parallel data providers launched from an XML suite. A suite can set data-provider-thread-count to change that count; provider thread-count configuration only takes effect when parallel mode is selected.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ParallelLoginTest {
    @DataProvider(name = "credentials", parallel = true)
    public Object[][] credentials() {
        return new Object[][] {
            {"alice", "correct-horse"},
            {"bob", "battery-staple"}
        };
    }

    @Test(dataProvider = "credentials")
    public void loginAcceptsCredentials(String username, String password) {
        // Exercise the behavior under test here.
    }
}
<suite name="tests" data-provider-thread-count="4">
    <test name="login">
        <classes>
            <class name="ParallelLoginTest"/>
        </classes>
    </test>
</suite>

The value 4 is an illustrative suite setting, not a performance recommendation or measured result. Confirm the suite attributes against the DTD and TestNG version used by your project.

Pool-sharing options in TestNG 7.9.0 and later

The documentation identifies two additional controls as available starting with TestNG 7.9.0:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
  • share-thread-pool-for-data-providers shares a pool among data-driven tests in a suite; its size is set by data-provider-thread-count.
  • use-global-thread-pool shares a pool for regular and data-driven tests; its size is set by thread-count.

These settings are version-bound. Check the TestNG version and suite DTD in your project before adding them; do not assume a configuration accepted by one version applies to another.

Check for shared-state hazards

Parallelism changes the execution conditions of your tests. Before enabling it, check whether invocations write to the same account, file, database record, or mutable test fixture. Isolate test data or coordinate access where needed. The TestNG documentation describes the concurrency settings, but it cannot establish that a particular application or test suite is safe to run concurrently.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choosing a provider layout

Approach Best fit Trade-off
Provider in the test class Data used by one test class or a small, local group of tests. Easy to find beside the consumer; sharing it across unrelated classes can create duplication.
Provider in a separate class Data reused across test classes. Centralizes shared cases; the provider method specified through dataProviderClass must be static.
Fixed rows A stable set of known input cases. Simple to inspect; each row must be maintained as cases change.
Method-aware provider Multiple test methods need a shared provider entry point but different data. Can reduce duplication; the method-selection logic needs maintenance as consumers change.
Sequential invocations Tests with shared state or no need for concurrent execution. Does not require enabling data-provider parallelism.
Parallel invocations Tests whose inputs and side effects are safe to execute concurrently. Requires concurrency-safe test design and suite/version-aware pool configuration.

Troubleshooting common DataProvider problems

  • TestNG cannot find the provider: Check that the string in dataProvider matches the provider name. If it is in another class, set dataProviderClass; if it is in the same class or a base class, verify its placement and annotation.
  • Test method arguments do not match the data: Compare every returned row with the consumer’s parameters in order. Each row must supply the arguments expected by that invocation.
  • External provider is not usable: When using dataProviderClass, confirm the named method is static, as required by the documentation.
  • Method-aware selection returns the wrong case or no case: Inspect the method-name branches and ensure every consumer using the provider is handled. An explicit exception for unknown consumers makes omissions easier to diagnose.
  • Configured provider thread count appears ignored: Confirm that parallel mode is enabled and that the suite runner and XML configuration are the ones actually being used. The documented provider thread-count setting only takes effect when parallel mode is selected.
  • Suite rejects a pool-sharing setting: Check the installed TestNG version and suite DTD. The two shared/global pool controls described above are documented as starting with TestNG 7.9.0.
  • Parallel tests fail inconsistently: Look for shared mutable state or test resources used by multiple invocations. Parallel configuration does not make those resources safe automatically.

Or skip the browser setup

TestNG DataProviders organize Java test inputs; if you also need website screenshots for a test or a development workflow, ScreenshotNeo is a separate screenshot API and MCP server. Its one-request API can capture a URL as an image or PDF. See the ScreenshotNeo documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners like a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up for 1,000 free screenshots a month, no card required.

Frequently Asked Questions

Where can I check which DataProvider options my installed TestNG version supports?

Use the TestNG documentation and the suite DTD that matches the version installed in your project; the documentation page is at testng.org/documentation.html.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.