JMeter中按顺序执行CRUD操作:多对象Token存储与复用问题咨询
Hey there! Let’s break down how to store those 10 tokens and reuse them for your GET/UPDATE/DELETE operations—this is a super common scenario in API testing, and there are straightforward solutions depending on the tools you’re using. Since you mentioned managing data with CSV, I’ll cover the most practical approaches below:
1. Using Postman/Newman (Popular API Testing Tool)
If you’re using Postman to run your tests, here’s how to handle multiple tokens:
- First, initialize an empty array: Go to your Environment variables, create a variable named
objectTokens, and set its initial value to[](an empty array). - Save tokens as you create objects: After each POST request to create an object, add this script to the "Tests" tab to capture the token and store it in the array:
// Pull the existing tokens array from the environment (or start empty) let currentTokens = pm.environment.get("objectTokens") || []; // Extract the token from the response (adjust the path to match your API's response structure) const newToken = pm.response.json().token; // Add the new token to the array currentTokens.push(newToken); // Save the updated array back to the environment pm.environment.set("objectTokens", currentTokens); - Reuse tokens for subsequent operations: When setting up your GET/UPDATE/DELETE requests, reference the token by its index (since you created objects in order, index 0 maps to the first object, index 9 to the 10th). For example:
- In the request header (if using Bearer auth), use
Bearer {{objectTokens}}[{{index}}] - If using Postman’s Collection Runner with a CSV, add an
indexcolumn to your CSV (values 0 to 9) to loop through each token automatically.
- In the request header (if using Bearer auth), use
2. Custom Scripting with Python + CSV
If you’re using a custom script to automate the workflow (great for full control), you can integrate token storage directly with your CSV:
- Step 1: Create objects and write tokens to CSV:
import csv import requests # List to store all object data + tokens object_records = [] # Create 10 objects for obj_num in range(1, 11): # Send POST request to create object (adjust URL and payload to match your API) create_response = requests.post( "https://your-api-endpoint.com/objects", json={"name": f"test_object_{obj_num}"} ) # Extract token from response obj_token = create_response.json()["token"] # Store object details + token object_records.append({ "object_id": obj_num, "token": obj_token, "initial_data": f"test_object_{obj_num}" }) # Write all data (including tokens) to your CSV with open("test_data.csv", "w", newline="", encoding="utf-8") as csv_file: fieldnames = ["object_id", "token", "initial_data"] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() writer.writerows(object_records) - Step 2: Read tokens from CSV for GET/UPDATE/DELETE:
# Read the CSV with stored tokens with open("test_data.csv", "r", encoding="utf-8") as csv_file: reader = csv.DictReader(csv_file) for row in reader: obj_token = row["token"] obj_id = row["object_id"] # Execute GET request get_response = requests.get( f"https://your-api-endpoint.com/objects/{obj_id}", headers={"Authorization": f"Bearer {obj_token}"} ) # Add your response validation here (e.g., check status code, data) # Execute UPDATE request update_response = requests.put( f"https://your-api-endpoint.com/objects/{obj_id}", json={"name": f"updated_object_{obj_id}"}, headers={"Authorization": f"Bearer {obj_token}"} ) # Execute DELETE request delete_response = requests.delete( f"https://your-api-endpoint.com/objects/{obj_id}", headers={"Authorization": f"Bearer {obj_token}"} )
3. JMeter (For Load Testing)
If you’re using JMeter, here’s how to manage multiple tokens:
- Initialize an array variable: Add a User Defined Variables element, create
objectTokenswith value[]. - Extract and store tokens: After your POST request, use a JSON Extractor to pull the token into a variable (e.g.,
extractedToken). Then add a JSR223 PostProcessor with this Groovy script to add the token to the array:// Get existing tokens array or start empty def tokensList = vars.get("objectTokens") ?: "[]" def tokens = new groovy.json.JsonSlurper().parseText(tokensList) // Add new token to the list tokens.add(vars.get("extractedToken")) // Save updated array back to variable vars.put("objectTokens", new groovy.json.JsonBuilder(tokens).toString()) - Reuse tokens: Use a Loop Controller set to 10 iterations. In your GET/UPDATE/DELETE requests, reference the token using:
${__groovy(vars.get("objectTokens")[vars.getIteration()],)}
Key Takeaways
The core concept here is using an array/list to store multiple tokens instead of a single variable. Depending on your tool, you can either:
- Store the array in environment/global variables (Postman/JMeter)
- Write the tokens directly back to your CSV file (custom scripts)
- Reference tokens by their index to match the order you created the objects in
内容的提问来源于stack exchange,提问作者Vittal

