如何在Gatling中从Feeder注入JSON至请求Body中
Got it, let's fix this up. The issue with your current code is that RawFileBody is meant to load static file content directly, but you need to dynamically generate a JSON body using the id value from your feeder. Here are two straightforward ways to achieve this:
Option 1: Use StringBody to Construct JSON Directly
Since your feeder provides an id value for each user, you can build the JSON body directly using Gatling's expression language to reference the feeder value:
.body(StringBody("""{"id":"${id}"}"""))
Triple quotes let you write the JSON string without escaping inner quotes, and ${id} pulls the current user's id from the feeder automatically.
Option 2: Use ElFileBody with a Template File
If you prefer keeping the JSON structure in a separate file (ideal for more complex bodies), create a template file (e.g., src/test/resources/json/gatling/request-template.json) with this content:
{"id":"${id}"}
Then reference this template in your request:
.body(ElFileBody("json/gatling/request-template.json"))
Gatling will replace the ${id} placeholder with the feeder's value for each user.
Full Modified Code
Here's your updated simulation class using Option 1 (swap in Option 2 if you prefer the template approach):
import io.gatling.core.Predef._ import io.gatling.http.Predef._ import scala.concurrent.duration._ class BasicSimulation extends Simulation { val httpConf = http .baseURL("http://localhost:8099") .headers(Map("Content-Type" -> "application/json")) .doNotTrackHeader("1") .acceptLanguageHeader("en-US,en;q=0.5") .acceptEncodingHeader("gzip, deflate") .userAgentHeader("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0") val feeder = jsonFile("src/test/resources/json/gatling/test.json") val scnPost = scenario("BasicSimulation") .feed(feeder) .exec(http("request_1") .post("/spring-test") // Use either StringBody or ElFileBody here .body(StringBody("""{"id":"${id}"}""")) .check(status.is(200))) setUp( scnPost.inject(constantUsersPerSec(3) during(3 seconds)) ).protocols(httpConf) }
How It Works
- The
.feed(feeder)step loads each entry from your JSON array into the user's session, making theidvalue accessible via${id}. - Both
StringBodyandElFileBodysupport Gatling's expression language, so they resolve the${id}placeholder to the actual feeder value for every user request.
内容的提问来源于stack exchange,提问作者a.moussa

