如何通过Newman命令或Java版Selenium动态调用Postman集合并按CSV序列执行?
1. Using Newman with a Script (Bash/Node.js)
Newman doesn’t natively support reading a CSV to execute collections in order, but we can use simple scripts to iterate through your CSV and run each collection sequentially.
Option 1: Bash Script (Unix/Linux/macOS)
First, structure your CSV (collection_sequence.csv) with a single column (header optional, but we’ll skip it in the script):
collection_name CreateA.json CreateB.json CreateA.json CreateB.json CreateA.json
Create a bash script named run_collections.sh:
#!/bin/bash # Skip the header line and loop through each collection tail -n +2 collection_sequence.csv | while read -r collection; do echo "=== Starting execution of $collection ===" newman run "$collection" # Optional: Stop early if a collection fails if [ $? -ne 0 ]; then echo "Error: $collection failed. Aborting sequence." exit 1 fi done echo "All collections ran successfully!"
Make the script executable and run it:
chmod +x run_collections.sh ./run_collections.sh
Option 2: Node.js Script (Cross-Platform)
For Windows or cross-platform support, use a Node.js script. First install the CSV parser dependency:
npm install csv-parser
Create run_collections.js:
const fs = require('fs'); const csv = require('csv-parser'); const { exec } = require('child_process'); // Helper function to run Newman and return a promise const runCollection = (collection) => { return new Promise((resolve, reject) => { console.log(`Running collection: ${collection}`); const newmanProcess = exec(`newman run "${collection}"`, (error, stdout, stderr) => { if (error) { console.error(`Failed to run ${collection}: ${error.message}`); reject(error); return; } console.log(stdout); if (stderr) console.warn(`Warnings from ${collection}: ${stderr}`); resolve(); }); }); }; // Read CSV and execute collections in order const main = async () => { const collections = []; fs.createReadStream('collection_sequence.csv') .pipe(csv()) .on('data', (row) => collections.push(row.collection_name)) .on('end', async () => { // Skip header (first entry) for (const coll of collections.slice(1)) { try { await runCollection(coll); } catch (err) { process.exit(1); } } console.log('✅ All collections executed successfully!'); }); }; main();
Run the script with:
node run_collections.js
2. Using Java (with Selenium Integration)
Selenium is focused on browser automation, but you can integrate Newman runs into your Java/Selenium workflow by executing Newman commands directly via Java’s ProcessBuilder. Here’s how:
Step 1: Ensure Newman is Installed
First, make sure Newman is globally installed on your system:
npm install -g newman
Step 2: Java Code to Run Collections from CSV
This class reads your CSV and runs each collection in sequence, which you can call from your Selenium test suite:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class NewmanCollectionRunner { public static void runCollection(String collectionPath) throws IOException, InterruptedException { System.out.println("Running collection: " + collectionPath); // Build Newman command (add options like -e for environment files if needed) ProcessBuilder pb = new ProcessBuilder("newman", "run", collectionPath); pb.inheritIO(); // Redirect Newman's output to the Java console Process process = pb.start(); int exitCode = process.waitFor(); if (exitCode != 0) { throw new RuntimeException("Collection " + collectionPath + " failed with exit code: " + exitCode); } } public static void main(String[] args) { String csvPath = "collection_sequence.csv"; try (BufferedReader br = new BufferedReader(new FileReader(csvPath))) { String line; br.readLine(); // Skip header line while ((line = br.readLine()) != null) { String collection = line.trim(); runCollection(collection); } System.out.println("All collections completed successfully!"); } catch (IOException | InterruptedException | RuntimeException e) { e.printStackTrace(); System.exit(1); } } }
Integration with Selenium
If you want to trigger Newman runs after specific Selenium actions (e.g., after logging into a web app), simply call the runCollection() method from your Selenium test code:
// Inside your Selenium test WebDriver driver = new ChromeDriver(); driver.get("https://your-app.com/login"); // Perform login steps... // Run a Postman collection after login NewmanCollectionRunner.runCollection("CreateA.json"); driver.quit();
内容的提问来源于stack exchange,提问作者Neeraj

