Karate框架中能否在URL与JSON数据中动态复用同一importid?
能否在Karate测试脚本的URL及后续JSON数据中动态替换并复用同一值?
场景背景
原测试脚本片段:
Background: * url 'yyy' And header Authorization = 'xxxxx' Scenario: read the csv file Given url 'xxxx' And multipart file importfile = {read:'datasets/zzzz.csv'} And multipart file entity = 'contact' When method POST And print response Then status 201 * def importid = response.data.import_id Then print importid # 需将此importid动态替换到下方URL中
后续需要复用importid的请求片段:
Given url 'https://' + importid + '/preview' # 需替换importid
JSON请求体片段:
{ "import_id": "importid", # 需替换为实际的importid值 "entity_columns": [ // 其他字段 ] }
需求说明
在Karate测试流程中,通过POST请求获取importid后,需将该值动态替换到后续请求的URL以及JSON请求体的import_id字段中,询问是否可实现该动态复用操作。
解决方案
完全可以实现,Karate原生支持这种变量复用场景,以下是具体实现方式:
1. URL动态拼接
直接在Given url中使用已定义的变量,Karate会自动解析变量值完成拼接:
* def importid = response.data.import_id Given url 'https://' + importid + '/preview'
2. JSON请求体动态替换
有两种常用的灵活实现方式:
方式一:使用Karate插值语法(#(变量名))
在JSON字符串中通过#(importid)直接引用变量,Karate会自动替换为实际值:
* def body = """ { "import_id": "#(importid)", "entity_columns": [ // 按需填写字段内容 ] } """
方式二:直接构造JSON对象
无需字符串拼接,直接用Karate的JSON对象语法绑定变量:
* def body = { import_id: importid, entity_columns: [] }
完整示例脚本
Background: * url 'yyy' And header Authorization = 'xxxxx' Scenario: 导入CSV并复用importid Given url 'xxxx' And multipart file importfile = {read:'datasets/zzzz.csv'} And multipart file entity = 'contact' When method POST Then status 201 * def importid = response.data.import_id Then print importid # 后续请求:使用importid拼接URL Given url 'https://' + importid + '/preview' # 构造带动态import_id的请求体 * def body = """ { "import_id": "#(importid)", "entity_columns": [ // 按需添加字段 ] } """ When method GET # 根据实际需求调整请求方法 Then status 200
内容的提问来源于stack exchange,提问作者Arun Sabee
相关产品推荐
相关产品推荐

