Data-Driven Testing in Postman — Running Collections with Multiple Datasets
In this tutorial, you will learn about Data. We cover key concepts, practical examples, and best practices to help you master this topic.
Data-driven testing in Postman runs the same collection multiple times with different input data from CSV or JSON files, enabling comprehensive test coverage with minimal test script duplication.
Code Example: CSV Data File for Threat Creation
name,severity,source_ip,expected_status,description
SQL Injection,high,192.168.1.1,201,Sensitive data exposure via SQL
XSS Attack,medium,10.0.0.50,201,Cross-site scripting in comments
Directory Traversal,high,172.16.0.1,201,Path traversal in file upload
Missing Name,low,10.0.0.1,422,Empty name field
Invalid IP,medium,not-an-ip,422,Invalid source IP format
Low Severity,low,192.168.1.99,201,Standard low severity alert
// Pre-request script — use data file values
const name = pm.iterationData.get("name");
const severity = pm.iterationData.get("severity");
const sourceIp = pm.iterationData.get("source_ip");
pm.variables.set("threatName", name);
pm.variables.set("threatSeverity", severity);
pm.variables.set("threatSourceIp", sourceIp);
// Log current iteration
console.log(`Iteration ${pm.info.iteration + 1}/${pm.info.iterationCount}`);
console.log(`Testing: name="${name}", severity="${severity}"`);
// Test script — validate against expected status
const expectedStatus = parseInt(pm.iterationData.get("expected_status"));
pm.test(`Status code is ${expectedStatus} for "${pm.iterationData.get("name")}"`, function () {
pm.response.to.have.status(expectedStatus);
});
pm.test("Response contains appropriate fields", function () {
const jsonData = pm.response.json();
if (expectedStatus === 201) {
pm.expect(jsonData).to.have.property("id");
pm.expect(jsonData).to.have.property("name");
pm.expect(jsonData.name).to.eql(pm.iterationData.get("name"));
} else {
pm.expect(jsonData).to.have.property("error");
}
});
Code Example: JSON Data File with Complex Objects
[
{
"scenario": "valid_threat",
"input": {
"name": "RCE Attempt",
"severity": "critical",
"source_ip": "10.0.0.100",
"tags": ["rce", "critical", "web"]
},
"expected": {
"status": 201,
"severity": "critical",
"has_tags": true
}
},
{
"scenario": "validation_error",
"input": {
"name": "AB",
"severity": "invalid",
"source_ip": "bad-ip"
},
"expected": {
"status": 422,
"error_field": "severity"
}
}
]
// Reading JSON data file
const input = pm.iterationData.get("input");
const expected = pm.iterationData.get("expected");
const scenario = pm.iterationData.get("scenario");
pm.variables.set("requestBody", JSON.stringify(input));
pm.test(`[${scenario}] Status code is ${expected.status}`, function () {
pm.response.to.have.status(expected.status);
});
pm.test(`[${scenario}] Response is correct`, function () {
const jsonData = pm.response.json();
if (expected.status === 201) {
pm.expect(jsonData.name).to.eql(input.name);
pm.expect(jsonData.severity).to.eql(expected.severity);
if (expected.has_tags) {
pm.expect(jsonData.tags).to.include.members(input.tags);
}
}
if (expected.error_field) {
pm.expect(jsonData.details).to.be.an("array");
const fields = jsonData.details.map(d => d.field);
pm.expect(fields).to.include(expected.error_field);
}
});
Code Example: Dynamic Data Generation Script
// Pre-request script — generate data if no data file is used
function generateThreatData() {
const severities = ["low", "medium", "high", "critical"];
const threatTypes = [
"SQL Injection", "XSS", "RCE", "Path Traversal",
"SSRF", "CSRF", "LDAP Injection", "XXE"
];
const type = threatTypes[Math.floor(Math.random() * threatTypes.length)];
const severity = severities[Math.floor(Math.random() * severities.length)];
return {
name: `Data-Driven ${type} - ${Date.now()}`,
severity: severity,
source_ip: `${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`,
tags: [type.toLowerCase(), severity, "automated"]
};
}
// Generate 5 unique threats for bulk creation
const threats = Array.from({length: 5}, generateThreatData);
pm.environment.set("bulkThreats", JSON.stringify(threats));
console.log(`Generated ${threats.length} test threats`);
Common Mistakes
1. CSV Column Name Mismatches
Column names in the CSV must exactly match the keys used in pm.iterationData.get(). Whitespace, case, and special characters matter.
2. Not Handling Data Variations
Data files mix valid and invalid inputs. Test scripts must handle both success and error responses based on the expected_status column.
3. Missing Data File Encoding
CSV files should be UTF-8 encoded. Special characters in data (accents, symbols) can cause Parsing issues with wrong encoding.
4. Overwriting Data Variables
Using the same variable name in both the data file and environment causes conflicts. Use distinct prefixes or namespaces.
5. Not Validating Data File Loading
CSV/JSON parsing errors fail silently. Validate the data file loads correctly by logging the number of iterations: console.log(pm.info.iterationCount).
Practice Questions
- What file formats does Postman support for data-driven testing?
- How do you access data file values in pre-request and test scripts?
- How do you handle both valid and invalid test cases in the same data file?
- What is the difference between CSV and JSON data files?
- How do you debug data-driven test iterations?
Answers:
- CSV (comma-separated values) and JSON (array of objects). CSV is simpler for flat data. JSON supports nested objects and arrays.
- Use pm.iterationData.get("columnName") for CSV and pm.iterationData.get("key") for JSON. Values are available in both pre-request and test scripts.
- Include an expected_status column/field. In test scripts, check the expected status and use conditional assertions for success vs error cases.
- CSV supports flat key-value pairs only. JSON supports nested objects, arrays, and mixed data types. JSON is better for complex test scenarios.
- Use console.log() to print iteration info: pm.info.iteration, pm.info.iterationCount. Check Postman Console for each iteration's output.
Challenge: Build a data-driven Postman test suite with a CSV file containing 20+ test cases (valid threats, invalid inputs, edge cases), JSON data file for complex scenarios, and comprehensive test scripts that handle both success and error responses.
FAQ
Mini Project
Build a data-driven Postman test suite for a threat intelligence API with: a 20-row CSV file covering valid and invalid threat creation, a JSON file for complex scenarios with nested validation, dynamic data fallback when no file is loaded, and a Newman CI script that runs the data-driven tests.
What's Next
Now learn about Postman Environments for managing configuration across dev, staging, and production.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro