簡體   English   中英

Scala - 如何在多行字符串文字中使用變量

[英]Scala - how to use variables in a multi-line string literal

我想調用“ myActionID ”變量的值。 我該怎么做? 如果我將像 "actionId":1368201 這樣的靜態值傳遞給 myActionID 那么它就可以工作,但是如果我使用 "actionId" : ${actionIdd} 它會出錯。

這是相關的代碼:

class LaunchWorkflow_Act extends Simulation {

    val scenarioRepeatCount = 1
    val userCount = 1
    val myActionID = "13682002351"
    
    val scn = scenario("LaunchMyFile")
        .repeat (scenarioRepeatCount) {
            exec(session => session.set("counter", (globalVar.getAndIncrement+" "+timeStamp.toString())))
            .exec(http("LaunchRequest")
            .post("""/api/test""")
            .headers(headers_0)
            .body(StringBody(
                """{    "actionId": ${myActionID} ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
                }""")))

            .pause(pause) 

        }
    }

setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)

如果我輸入值 13682002351 而不是 myActionID,一切正常。 在 Gatling 中執行此腳本時,出現此錯誤

錯誤 ighttp.action.HttpRequestAction - 'httpRequest-3' 執行失敗:未定義名為 'myActionID' 的屬性

Scala 有各種字符串插值機制(參見文檔),可用於在字符串中嵌入變量。 所有這些都可以與用於創建多行字符串的三重引號"""使用。

在這種情況下,您可以使用:

val counter = 12
val myActionID = "13682002351"
val str = s"""{    
                "actionId": $myActionID ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
              }"""

注意字符串字面前的s和變量名前的美元符號。

使用S 內插字符串,我們可以輕松做到這一點:

 s"""Hello Word , Welcome Back!
      How are you doing ${userName}"""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM