You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Gatling扩展自定义DSL:Scala实现方法问询

问题:实现可在Gatling的ScenarioBuilder和ChainBuilder通用的可组合扩展方法

我们使用Gatling对应用进行负载测试,效果良好。为遵循DRY原则实现代码复用,尝试对Gatling的ScenarioBuilder、ChainBuilder等类(位于io.gatling.core.structure包)进行可组合扩展。

现有场景示例代码如下:

val scn = scenario("Whatever")
  .exec(Authentication.FeederLogin(userCsvFile, password))
  .exec(User.ExtractId(User.SignIn()))
  .exec(FindPeople(50, "personIds")) // SPA load
  .exec(User.FetchLandingPageFor("${userId}"))
  .during(durationSeconds.seconds) {
    pace(3.seconds, 8.seconds)
      .exec(Person.Search("${personIds.random()}"))
      .pause(3.seconds, 10.seconds)
      // start the upload
      .exec(Upload.create())
  }

我们期望实现可组合的扩展方法以在其他场景中复用,设想代码如下:

val scn = scenario("Whatever")
  .login()
  .during(durationSeconds.seconds) {
    pace(3.seconds, 8.seconds)
      .uploadFor("${personIds.random()}")
  }

// ...
object WhateverScenarios {
  implicit class ScenarioBuilderWithWhatevers(b: ScenarioBuilder) {
    def login() : ScenarioBuilder = {
      b.exec(Authentication.FeederLogin(userCsvFile, password))
        .exec(User.ExtractId(User.SignIn()))
        .exec(FindPeople(50, "personIds"))
    }

    def uploadFor(whom : String): ScenarioBuilder = {
      b.exec(Person.Search("${personIds.random()}"))
        .pause(3.seconds, 10.seconds)
        // start the upload
        .exec(Upload.create())
    }
  }
}

目前上述代码可运行,但存在问题:uploadFor方法在ChainBuilder上下文(而非ScenarioBuilder)中无法使用。我们尝试用泛型解决,发现这些类均继承StructureBuilder[T],但无法定义合适的泛型实现,使自定义扩展可在任意StructureBuilder[T]上下文中使用,恳请提供解决方案。

内容的提问来源于stack exchange,提问作者Levi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:32:35