Karate 中如何在多行字符串内插入变量?
Karate DSL多行字符串嵌入变量实现方案
你当前的写法存在变量名拼写不匹配的问题:定义的变量为createDate,注入时写为#createdDate,多了字母d,修正拼写后即可使用Karate内置的变量注入能力。
实现方案
方案1:直接使用Karate内置表达式注入(最推荐,JSON场景优先用)
Karate原生支持在三个双引号包裹的多行字符串中,通过#变量名的格式直接注入已定义的变量,修正后的示例代码如下:
* def LocalDateTime = Java.type('java.time.LocalDateTime') * def createDate = LocalDateTime.now() And request """ { "id": 444444, "date": "#createDate" } """
方案2:对象操作后作为请求体(适合需要复杂动态修改的场景)
如果需要动态增删字段、做逻辑判断,可先定义请求体对象,再通过set语法修改属性,无需手动拼接JSON:
* def LocalDateTime = Java.type('java.time.LocalDateTime') // 先定义基础请求体 * def reqBody = { id: 444444 } // 动态添加日期属性 * set reqBody.date = LocalDateTime.now() // 直接传入对象作为请求体 And request reqBody
方案3:字符串拼接(仅适合纯文本场景,JSON场景不推荐)
如果是普通文本多行字符串,可通过字符串拼接的方式嵌入变量:
* def createDate = LocalDateTime.now().toString() And request """ { "id": 444444, "date": ' + createDate + ' } """
额外注意
如果接口要求特定格式的日期字符串,需要先对LocalDateTime做格式化,避免直接传入对象导致序列化异常,示例如下:
* def LocalDateTime = Java.type('java.time.LocalDateTime') * def DateTimeFormatter = Java.type('java.time.format.DateTimeFormatter') // 自定义日期格式 * def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") * def createDate = LocalDateTime.now().format(formatter)
内容的提问来源于stack exchange,提问作者Mejmo
相关产品推荐
相关产品推荐

