DATA-DRIVEN TESTING: TESTNG @DATAPROVIDER, CSV & JSON

Architect high-coverage, parameterized test matrices in REST Assured: TestNG @DataProvider mechanics, static Object[][] arrays, Iterator<Object[]> lazy streaming, CSV ingestion via OpenCSV/Commons-CSV, Jackson TypeReference JSON datasets, parallel data providers (parallel = true), and Method parameter reflection.

πŸ“Š Parameterized Test Matrices, External Ingestion & Concurrency Governance

Hardcoding static input values and expected HTTP status assertions directly within test methods limits regression depth and duplicates assertion logic across boundary conditions. Data-Driven Testing (DDT) decouples test execution algorithms from underlying test data fixtures. By leveraging TestNG's @DataProvider annotation in conjunction with REST Assured, automation engineers supply dynamic two-dimensional data arrays (Object[][]) or lazy streams (Iterator<Object[]>) directly into test method parameters. Whether ingesting high-volume tabular boundaries via CSV (OpenCSV / Apache Commons CSV), unmarshalling hierarchical permutations from JSON fixtures via Jackson Databind, or accelerating test execution across multi-threaded workers with parallel = true, parameterized testing establishes scalable, reusable, and comprehensive regression verification across enterprise REST APIs.

1. TestNG DataProvider Architecture & REST Assured Parameter Injection
The architectural pipeline of TestNG data-driven execution, illustrating how external CSV files, JSON fixtures, and in-memory matrices are ingested, mapped into typed POJOs or Object arrays, and dispatched into parallel REST Assured execution threads.
TestNG DataProvider Ingestion & Concurrency Topography
TESTNG @DATAPROVIDER EXECUTION PIPELINE & DATA INGESTION:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ EXTERNAL DATA SOURCES (src/test/resources/data/)                                              β”‚
β”‚  β”œβ”€β”€ CSV File: students-boundary.csv (Fast tabular boundary rows: id, credits, expectedCode)  β”‚
β”‚  β”œβ”€β”€ JSON Fixture: student-payloads.json (Hierarchical multi-level nested payloads)           β”‚
β”‚  └── In-Memory Java Array: Object[][] (Inline quick boundary checks)                          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Parsed by OpenCSV / Jackson ObjectMapper)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ @DataProvider(name = "studentDataProvider", parallel = true)                                  β”‚
β”‚  β”œβ”€β”€ Returns Object[][] or Iterator<Object[]>                                                 β”‚
β”‚  β”œβ”€β”€ Row 1: ["STU-101", "Nikita Sharma", 16, 200, "SUCCESS"]                                  β”‚
β”‚  β”œβ”€β”€ Row 2: ["STU-102", "Aarav Deshmukh", 0,  422, "CREDITS_BELOW_MINIMUM"]                   β”‚
β”‚  └── Row 3: ["STU-999", "Unknown Record", 12, 404, "NOT_FOUND"]                               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β–Ό (Distributed Concurrently across Worker Threads)     β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ WORKER THREAD-1 (Row 1 Execution)            β”‚      β”‚ WORKER THREAD-2 (Row 2 Execution)            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€      β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ @Test(dataProvider = "studentDataProvider")  β”‚      β”‚ @Test(dataProvider = "studentDataProvider")  β”‚
β”‚ public void testEnrollment(id, name, cr, ..) β”‚      β”‚ public void testEnrollment(id, name, cr, ..) β”‚
β”‚                                              β”‚      β”‚                                              β”‚
β”‚ given()                                      β”‚      β”‚ given()                                      β”‚
β”‚   .baseUri("https://staging-api...")         β”‚      β”‚   .baseUri("https://staging-api...")         β”‚
β”‚   .body(new StudentDTO(id, name, cr))        β”‚      β”‚   .body(new StudentDTO(id, name, cr))        β”‚
β”‚ .when().post("/students/enroll")             β”‚      β”‚ .when().post("/students/enroll")             β”‚
β”‚ .then().statusCode(expectedCode); // 200     β”‚      β”‚ .then().statusCode(expectedCode); // 422     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: TestNG data providers can return either Object[][] (materializing all test rows in memory upfront) or Iterator<Object[]> (streaming rows lazily on-demand). For large CSV or JSON files with thousands of permutations, prefer Iterator<Object[]> to preserve JVM heap memory.
Real-Time Example 1: In-Memory Multi-Dimensional Object[][] DataProvider
Building a clean, inline @DataProvider returning a two-dimensional Object[][] array. Demonstrates testing multiple HTTP boundary conditions (valid credits, zero credits, negative credits) against a single parameterized REST Assured test method.
Java (Inline Object[][] TestNG DataProvider)
package com.nikita.restassured.datadriven;

import io.restassured.http.ContentType;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.HashMap;
import java.util.Map;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class BasicObjectArrayDataProviderTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    // DataProvider returning static 2D array of inputs and expected outcomes
    @DataProvider(name = "creditValidationData")
    public Object[][] provideCreditBoundaryData() {
        return new Object[][] {
            // Scenario 1: Valid standard credits (HTTP 200)
            { "STU-88219", 16, 200, "SUCCESS" },
            // Scenario 2: Minimum allowable boundary (HTTP 200)
            { "STU-88220", 1,  200, "SUCCESS" },
            // Scenario 3: Maximum allowable boundary (HTTP 200)
            { "STU-88221", 30, 200, "SUCCESS" },
            // Scenario 4: Negative edge - Zero credits (HTTP 422 Unprocessable)
            { "STU-88222", 0,  422, "CREDITS_BELOW_MINIMUM" },
            // Scenario 5: Negative edge - Exceeding maximum cap (HTTP 422 Unprocessable)
            { "STU-88223", 35, 422, "CREDITS_EXCEED_MAXIMUM" }
        };
    }

    @Test(dataProvider = "creditValidationData",
          description = "Parameterized validation of credit boundary conditions using in-memory Object[][]")
    public void testCreditBoundaries(String studentId, int credits, int expectedStatusCode, String expectedStatusMsg) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("studentId", studentId);
        payload.put("enrolledCredits", credits);

        given()
            .baseUri(BASE_URI)
            .contentType(ContentType.JSON)
            .body(payload)
            .log().ifValidationFails()
        .when()
            .post("/students/credits/validate")
        .then()
            .log().ifValidationFails()
            // Dynamic assertions bound directly to DataProvider parameters:
            .statusCode(expectedStatusCode)
            .body("status", equalTo(expectedStatusMsg));

        System.out.printf("[βœ”] Parameterized Case Passed: ID=%s | Credits=%d βž” Status=%d (%s)%n",
                studentId, credits, expectedStatusCode, expectedStatusMsg);
    }
}
Execution Output (5 Invocations of testCreditBoundaries): [βœ”] Parameterized Case Passed: ID=STU-88219 | Credits=16 βž” Status=200 (SUCCESS) [βœ”] Parameterized Case Passed: ID=STU-88220 | Credits=1 βž” Status=200 (SUCCESS) [βœ”] Parameterized Case Passed: ID=STU-88221 | Credits=30 βž” Status=200 (SUCCESS) [βœ”] Parameterized Case Passed: ID=STU-88222 | Credits=0 βž” Status=422 (CREDITS_BELOW_MINIMUM) [βœ”] Parameterized Case Passed: ID=STU-88223 | Credits=35 βž” Status=422 (CREDITS_EXCEED_MAXIMUM) PASSED: testCreditBoundaries (5/5 scenarios executed with single test method)
Real-Time Example 2: Ingesting Tabular Test Data from CSV Files via OpenCSV
Decoupling test data into external CSV spreadsheets. Uses OpenCSV's CSVReader inside a TestNG @DataProvider to parse test rows from src/test/resources/data/student-registration.csv and feed parameters dynamically.
Java & CSV: Ingesting External CSV Test Fixtures
// ==============================================================================
// CSV FILE LOCATION: src/test/resources/data/student-registration.csv
// ==============================================================================
// fullName,email,academicTrack,enrolledCredits,expectedCode
// Nikita Sharma,nikita.sharma@nikita-infotech.com,ENTERPRISE_AUTOMATION,16,201
// Aarav Deshmukh,aarav.deshmukh@nikita-infotech.com,FULLSTACK_SDET,12,201
// Rohan Verma,rohan.verma@nikita-infotech.com,CLOUD_DEVOPS_QA,8,201
// Invalid Student,broken-email-format,ENTERPRISE_AUTOMATION,10,400

package com.nikita.restassured.datadriven;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import io.restassured.http.ContentType;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.restassured.RestAssured.given;

public class CsvDataProviderTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    @DataProvider(name = "csvStudentDataProvider")
    public Object[][] readStudentDataFromCsv() throws IOException, CsvException {
        String csvPath = "src/test/resources/data/student-registration.csv";
        List<Object[]> testData = new ArrayList<>();

        try (CSVReader reader = new CSVReader(new FileReader(csvPath))) {
            List<String[]> allRows = reader.readAll();
            
            // Skip CSV header line (index 0) and process data rows:
            for (int i = 1; i < allRows.size(); i++) {
                String[] row = allRows.get(i);
                testData.add(new Object[] {
                    row[0],                          // fullName
                    row[1],                          // email
                    row[2],                          // academicTrack
                    Integer.parseInt(row[3].trim()), // enrolledCredits
                    Integer.parseInt(row[4].trim())  // expectedCode
                });
            }
        }

        return testData.toArray(new Object[0][]);
    }

    @Test(dataProvider = "csvStudentDataProvider",
          description = "Parameterized API registration driven entirely by external CSV rows")
    public void testStudentRegistrationFromCsv(String name, String email, String track, int credits, int expectedCode) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("fullName", name);
        requestBody.put("email", email);
        requestBody.put("academicTrack", track);
        requestBody.put("enrolledCredits", credits);

        given()
            .baseUri(BASE_URI)
            .contentType(ContentType.JSON)
            .body(requestBody)
        .when()
            .post("/students")
        .then()
            .statusCode(expectedCode);

        System.out.printf("[CSV DDT] Processed Candidate: %s (%s) βž” HTTP %d%n", name, track, expectedCode);
    }
}
CSV Ingestion Output: [CSV DDT] Processed Candidate: Nikita Sharma (ENTERPRISE_AUTOMATION) βž” HTTP 201 [CSV DDT] Processed Candidate: Aarav Deshmukh (FULLSTACK_SDET) βž” HTTP 201 [CSV DDT] Processed Candidate: Rohan Verma (CLOUD_DEVOPS_QA) βž” HTTP 201 [CSV DDT] Processed Candidate: Invalid Student (ENTERPRISE_AUTOMATION) βž” HTTP 400 PASSED: testStudentRegistrationFromCsv (4/4 scenarios successfully executed from external CSV)
Real-Time Example 3: Ingesting Hierarchical JSON Test Fixtures via Jackson Databind
Handling complex, deeply nested JSON test inputs. Reads an array of complex scenario objects from students-payload.json using Jackson's TypeReference and streams them into REST Assured test methods as typed Java POJOs.
Java & JSON: Ingesting Complex JSON Array Payloads into POJOs
// ==============================================================================
// JSON FIXTURE: src/test/resources/data/students-payload.json
// ==============================================================================
// [
//   {
//     "fullName": "Nikita Sharma",
//     "academicTrack": "ENTERPRISE_AUTOMATION",
//     "contact": { "phone": "+91-9096808284", "city": "Pune" },
//     "expectedStatus": 201
//   },
//   {
//     "fullName": "Aarav Deshmukh",
//     "academicTrack": "FULLSTACK_SDET",
//     "contact": { "phone": "+91-9876543210", "city": "Mumbai" },
//     "expectedStatus": 201
//   }
// ]

package com.nikita.restassured.datadriven;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.http.ContentType;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class JsonFixtureDataProviderTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    @DataProvider(name = "jsonFixtureDataProvider")
    public Object[][] readJsonFixtures() throws IOException {
        File jsonFile = new File("src/test/resources/data/students-payload.json");
        ObjectMapper mapper = new ObjectMapper();

        // Deserialize JSON array into List of generic Maps (or custom POJO models)
        List<Map<String, Object>> scenarios = mapper.readValue(
                jsonFile, 
                new TypeReference<List<Map<String, Object>>>() {}
        );

        List<Object[]> data = new ArrayList<>();
        for (Map<String, Object> scenario : scenarios) {
            int expectedStatus = (Integer) scenario.remove("expectedStatus");
            data.add(new Object[] { scenario, expectedStatus });
        }

        return data.toArray(new Object[0][]);
    }

    @Test(dataProvider = "jsonFixtureDataProvider",
          description = "Execute multi-level nested POST registration from external JSON fixtures")
    public void testComplexJsonRegistration(Map<String, Object> payload, int expectedStatus) {
        given()
            .baseUri(BASE_URI)
            .contentType(ContentType.JSON)
            .body(payload)
        .when()
            .post("/students/nested-registration")
        .then()
            .statusCode(expectedStatus)
            .body("status", equalTo("SUCCESS"));

        System.out.println("[JSON DDT] Successfully processed nested payload for: " + payload.get("fullName"));
    }
}
JSON Ingestion Trace: [JSON DDT] Successfully processed nested payload for: Nikita Sharma [JSON DDT] Successfully processed nested payload for: Aarav Deshmukh PASSED: testComplexJsonRegistration (2/2 nested scenarios executed cleanly)
Real-Time Example 4: Memory-Efficient Lazy Streaming via Iterator<Object[]>
Preventing OutOfMemory errors when running large datasets. Returns an Iterator<Object[]> from the @DataProvider to stream data rows on-demand from disk rather than buffering millions of rows in JVM heap memory.
Java (Memory-Efficient Lazy Iterator Streaming)
package com.nikita.restassured.datadriven;

import com.opencsv.CSVReader;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.FileReader;
import java.util.Iterator;

import static io.restassured.RestAssured.given;

public class LazyStreamingDataProviderTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    @DataProvider(name = "lazyCsvStreamProvider")
    public Iterator<Object[]> streamLargeCsvData() {
        return new Iterator<>() {
            private CSVReader reader;
            private String[] nextLine;

            {
                try {
                    reader = new CSVReader(new FileReader("src/test/resources/data/large-dataset.csv"));
                    reader.readNext(); // Skip CSV header
                    advance();
                } catch (Exception e) {
                    throw new RuntimeException("Failed to initialize streaming CSV reader", e);
                }
            }

            private void advance() {
                try {
                    nextLine = reader.readNext();
                    if (nextLine == null) {
                        reader.close();
                    }
                } catch (Exception e) {
                    nextLine = null;
                }
            }

            @Override
            public boolean hasNext() {
                return nextLine != null;
            }

            @Override
            public Object[] next() {
                Object[] dataRow = new Object[] { nextLine[0], Integer.parseInt(nextLine[1]) };
                advance();
                return dataRow;
            }
        };
    }

    @Test(dataProvider = "lazyCsvStreamProvider",
          description = "Execute high-volume data-driven test using lazy streaming iterator")
    public void testHighVolumeStreaming(String studentId, int expectedCredits) {
        given()
            .baseUri(BASE_URI)
            .pathParam("id", studentId)
        .when()
            .get("/students/{id}/credits")
        .then()
            .statusCode(200);

        System.out.printf("[STREAMING DDT] Verified Record: %s with credits: %d%n", studentId, expectedCredits);
    }
}
Streaming Execution Telemetry: [STREAMING DDT] Verified Record: STU-88219 with credits: 16 [STREAMING DDT] Verified Record: STU-88220 with credits: 12 ... (Streams rows sequentially without loading entire file into JVM memory) Heap Allocation: Flat memory profile maintained across 10,000+ data rows.
Real-Time Example 5: High-Concurrency Parallel Execution (parallel = true)
Accelerating test suite throughput. Configures @DataProvider(parallel = true) and manages thread counts via TestNG XML configuration to execute parameterized test iterations across concurrent worker threads safely.
Java & XML: Parallel DataProvider Concurrency Configuration
package com.nikita.restassured.datadriven;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class ParallelDataProviderTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    // parallel = true enables TestNG to distribute rows across concurrent worker threads
    @DataProvider(name = "parallelStudentProvider", parallel = true)
    public Object[][] provideParallelTestData() {
        return new Object[][] {
            { "STU-88219", "Nikita Sharma" },
            { "STU-88220", "Aarav Deshmukh" },
            { "STU-88221", "Rohan Verma" },
            { "STU-88222", "Pooja Patil" }
        };
    }

    @Test(dataProvider = "parallelStudentProvider",
          description = "Execute parameterized scenarios concurrently across parallel threads")
    public void testParallelStudentLookup(String studentId, String expectedName) {
        long threadId = Thread.currentThread().getId();
        System.out.printf("[Thread-%d] START: Querying ID: %s (%s)%n", threadId, studentId, expectedName);

        given()
            .baseUri(BASE_URI)
            .pathParam("id", studentId)
        .when()
            .get("/students/{id}")
        .then()
            .statusCode(200)
            .body("fullName", equalTo(expectedName));

        System.out.printf("[Thread-%d] FINISH: Verified ID: %s%n", threadId, studentId);
    }
}

// ==============================================================================
// TESTNG XML CONFIGURATION: src/test/resources/testng-parallel.xml
// ==============================================================================
// <suite name="ParallelDataSuite" data-provider-thread-count="4">
//   <test name="ParallelDataProviderTests">
//     <classes>
//       <class name="com.nikita.restassured.datadriven.ParallelDataProviderTest"/>
//     </classes>
//   </test>
// </suite>
Parallel Execution Telemetry (4 Concurrent Threads): [Thread-24] START: Querying ID: STU-88219 (Nikita Sharma) [Thread-25] START: Querying ID: STU-88220 (Aarav Deshmukh) [Thread-26] START: Querying ID: STU-88221 (Rohan Verma) [Thread-27] START: Querying ID: STU-88222 (Pooja Patil) [Thread-24] FINISH: Verified ID: STU-88219 [Thread-26] FINISH: Verified ID: STU-88221 [Thread-25] FINISH: Verified ID: STU-88220 [Thread-27] FINISH: Verified ID: STU-88222 Execution Time: ~140ms total (4x throughput improvement over sequential execution)
Real-Time Example 6: Dynamic Data Filtering via Method Parameter Reflection
Reusing a single @DataProvider across multiple test methods. Uses Java reflection (java.lang.reflect.Method) to inspect the calling test method name and selectively return specific data subsets (Smoke vs. Regression).
Java (Method Reflection Driven DataProvider)
package com.nikita.restassured.datadriven;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.lang.reflect.Method;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class MethodReflectionDataProviderTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    // Single DataProvider serving different data subsets based on calling Method reflection
    @DataProvider(name = "contextualStudentDataProvider")
    public Object[][] provideContextualData(Method method) {
        String testMethodName = method.getName();
        System.out.println("[*] DataProvider dynamically resolving data for calling method: " + testMethodName);

        if (testMethodName.equals("testSmokeTierStudents")) {
            // Return minimal smoke test subset
            return new Object[][] {
                { "STU-88219", "Nikita Sharma", 200 }
            };
        } else if (testMethodName.equals("testComprehensiveRegressionStudents")) {
            // Return full multi-row regression dataset
            return new Object[][] {
                { "STU-88219", "Nikita Sharma", 200 },
                { "STU-88220", "Aarav Deshmukh", 200 },
                { "STU-88221", "Rohan Verma", 200 },
                { "STU-NON-EXISTENT", "Unknown", 404 }
            };
        }

        return new Object[][] {};
    }

    @Test(dataProvider = "contextualStudentDataProvider",
          description = "Smoke test executing fast single-record validation")
    public void testSmokeTierStudents(String id, String expectedName, int expectedStatus) {
        given()
            .baseUri(BASE_URI)
            .pathParam("id", id)
        .when()
            .get("/students/{id}")
        .then()
            .statusCode(expectedStatus)
            .body("fullName", equalTo(expectedName));

        System.out.println("[SMOKE PASS] Verified: " + id);
    }

    @Test(dataProvider = "contextualStudentDataProvider",
          description = "Full regression test executing exhaustive multi-record dataset")
    public void testComprehensiveRegressionStudents(String id, String expectedName, int expectedStatus) {
        given()
            .baseUri(BASE_URI)
            .pathParam("id", id)
        .when()
            .get("/students/{id}")
        .then()
            .statusCode(expectedStatus);

        System.out.println("[REGRESSION PASS] Verified: " + id + " βž” Status: " + expectedStatus);
    }
}
Reflection Dispatch Telemetry: [*] DataProvider dynamically resolving data for calling method: testSmokeTierStudents [SMOKE PASS] Verified: STU-88219 (1 scenario executed) [*] DataProvider dynamically resolving data for calling method: testComprehensiveRegressionStudents [REGRESSION PASS] Verified: STU-88219 βž” Status: 200 [REGRESSION PASS] Verified: STU-88220 βž” Status: 200 [REGRESSION PASS] Verified: STU-88221 βž” Status: 200 [REGRESSION PASS] Verified: STU-NON-EXISTENT βž” Status: 404 (4 scenarios executed)
Real-Time Example 7: Centralizing Data Providers via External DataProviderClass
Architecting modular, maintainable test suites. Centralizes data extraction logic into a dedicated standalone factory class (StudentDataProviders.java) and references it cleanly via dataProviderClass.
Java (External DataProviderClass Architecture)
package com.nikita.restassured.datadriven;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

// ==============================================================================
// FACTORY CLASS: Holds all reusable DataProviders across the test suite
// ==============================================================================
class StudentDataProviders {

    @DataProvider(name = "globalActiveStudents")
    public static Object[][] getActiveStudents() {
        return new Object[][] {
            { "STU-88219", "ENTERPRISE_AUTOMATION" },
            { "STU-88220", "FULLSTACK_SDET" }
        };
    }

    @DataProvider(name = "globalSuspendedStudents")
    public static Object[][] getSuspendedStudents() {
        return new Object[][] {
            { "STU-77100", "PROBATION" },
            { "STU-77101", "SUSPENDED" }
        };
    }
}

// ==============================================================================
// TEST CLASS: Consumes DataProvider from external class
// ==============================================================================
public class ExternalDataProviderClassTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    @Test(dataProvider = "globalActiveStudents", 
          dataProviderClass = StudentDataProviders.class,
          description = "Consume DataProvider defined inside external StudentDataProviders class")
    public void testActiveStudentsExternalProvider(String studentId, String expectedTrack) {
        given()
            .baseUri(BASE_URI)
            .pathParam("id", studentId)
        .when()
            .get("/students/{id}")
        .then()
            .statusCode(200)
            .body("academicTrack", equalTo(expectedTrack));

        System.out.printf("[EXTERNAL PROVIDER] Verified Student %s in track: %s%n", studentId, expectedTrack);
    }
}
External Provider Output: [EXTERNAL PROVIDER] Verified Student STU-88219 in track: ENTERPRISE_AUTOMATION [EXTERNAL PROVIDER] Verified Student STU-88220 in track: FULLSTACK_SDET Decouples data extraction logic from test classes, making data fixtures reusable across multiple suites.
Real-Time Example 8: Debugging Parameter Mismatches & DataProvider Triage
Troubleshooting common TestNG data-driven defects: diagnosing TestNGException: Method has dataProvider but its types are not compatible, fixing column-to-parameter count mismatches, and handling unparsed CSV data types.
Java (Triage: Parameter Signature & Type Compatibility Defects)
package com.nikita.restassured.datadriven;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderTriageTest {

    // ==========================================================================
    // COMMON PITFALL: PARAMETER SIGNATURE MISMATCH
    // SYMPTOM: org.testng.TestNGException:
    // Method public void testMethod(String, int) requires 2 parameters but
    // DataProvider supplied 3 parameters: [STU-88219, 16, EXTRA_PARAMETER]
    //
    // CAUSE: The @Test method signature does not match the Object[] row length!
    // FIX: Ensure @Test arguments match the exact count and types supplied by the provider.
    // ==========================================================================

    @DataProvider(name = "triageProvider")
    public Object[][] provideTriageData() {
        return new Object[][] {
            // Supplies 2 parameters: String id, int credits
            { "STU-88219", 16 }
        };
    }

    // RESOLVED: Test method signature accepts exactly (String studentId, int credits)
    @Test(dataProvider = "triageProvider",
          description = "Verify test method signature correctly aligns with DataProvider parameters")
    public void testResolvedParameterSignature(String studentId, int credits) {
        System.out.printf("[βœ”] Correctly mapped parameters: ID=%s (String), Credits=%d (int)%n", 
                studentId, credits);
    }

    // ==========================================================================
    // PITFALL 2: STRING INGESTION FROM CSV AS NUMERIC PRIMITIVE
    // CSV readers return Strings by default: "16" instead of 16!
    // Passing "16" to a method expecting int credits causes IllegalArgumentException.
    // FIX: Parse strings explicitly via Integer.parseInt() inside the DataProvider!
    // ==========================================================================
}
Triage Diagnostic Breakdown: Failure Symptom: TestNGException: Method requires 2 parameters but DataProvider supplied 3. Root Cause: DataProvider row length does not match @Test method signature. Fix Applied: Aligned method parameters (String, int) with the supplied Object[] elements. Result: Parameters map cleanly with zero reflection errors.
Real-Time Example 9: Data-Driven Testing Specification Reference Matrix
A comprehensive reference summary pairing TestNG DataProvider annotations, return types, data sources, concurrency controls, and operational best practices for REST Assured automation architects.
TestNG DataProvider Specification Reference Matrix
TESTNG @DATAPROVIDER SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ COMPONENT / ATTRIBUTE   β”‚ METHOD SIGNATURE / VALUE     β”‚ RETURN TYPE      β”‚ PRIMARY OPERATIONAL PURPOSE   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ @DataProvider(name=..)  β”‚ @DataProvider(name="name")   β”‚ Object[][]       β”‚ In-memory 2D array provider   β”‚
β”‚ Lazy Streaming Provider β”‚ Iterator<Object[]>           β”‚ Iterator<Object[]>Streams large datasets on-demandβ”‚
β”‚ Parallel Concurrency    β”‚ @DataProvider(parallel=true) β”‚ Boolean (true)   β”‚ Dispatches rows in parallel   β”‚
β”‚ External Provider Class β”‚ dataProviderClass = Cls.classβ”‚ Class Reference  β”‚ Reusable shared provider classβ”‚
β”‚ Method Reflection       β”‚ public Object[][] prov(Method)java.lang.Method  β”‚ Filters data by caller method β”‚
β”‚ OpenCSV Integration     β”‚ CSVReader.readAll()          β”‚ List<String[]>   β”‚ Parses external CSV data rows β”‚
β”‚ Jackson JSON Fixture    β”‚ mapper.readValue(File, TypeR)List<Map<String>>  β”‚ Ingests nested JSON payloads  β”‚
β”‚ Parallel Thread Count   β”‚ data-provider-thread-count   β”‚ TestNG XML suite β”‚ Controls parallel thread pool β”‚
β”‚ Parameter Mapping       β”‚ @Test(dataProvider="name")   β”‚ Method Arguments β”‚ Injects row fields into @Test β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 DATA-DRIVEN TESTING BEST PRACTICES:                                                                 β”‚
β”‚ 1. Use external CSV files for tabular boundary tests: Decouple test data fixtures from test scripts.      β”‚
β”‚ 2. Ingest JSON fixtures for complex nested payloads: Use Jackson TypeReference to parse scenario files    β”‚
β”‚ 3. Enable parallel = true on high-volume providers: Accelerate test execution across multiple threads.    β”‚
β”‚ 4. Return Iterator<Object[]> for large datasets: Stream rows lazily to prevent heap OutOfMemory errors    β”‚
β”‚ 5. Centralize providers in dedicated classes: Use dataProviderClass to share datasets across suites.      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Data-Driven Testing transforms hardcoded tests into reusable, high-coverage validation matrices. By combining TestNG's @DataProvider with external CSV parsers, Jackson JSON fixture ingestion, parallel thread execution, and reflection-based filtering, you build scalable, maintainable test frameworks that maximize test coverage across edge conditions.