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

如何在Karate DSL中利用前序场景响应数据构造动态URL

Karate DSL 跨场景提取响应值构造后续请求URL实现方法

Karate默认不同Scenario的变量互相隔离,你只需将第一个场景需要共享的字段设置为Feature级别作用域的变量,就可以在同文件的后续场景直接调用。

步骤1:修改第一个场景,存储目标字段

场景:Get test 1
Given       url 'http://UrlOfMyTest/ApiTest/'
And         header Content-Type = 'application/json'
And         header Authorization = token
When        method get
Then        status 200
And         print 'The Response of "information" is: ', response.objects[0]."name of the field"
# 新增:将目标字段存储为Feature级共享变量
*           karate.set('preFieldValue', response.objects[0]."name of the field", 'feature')

步骤2:第二个场景直接调用变量拼接URL

场景2:Get test 2
# 直接用存储的变量拼接URL,两种写法都支持
# 写法1:字符串拼接
Given       url 'http://UrlOfMyTest/ApiTest/' + preFieldValue
# 写法2:Karate字符串插值
# Given     url 'http://UrlOfMyTest/ApiTest/${preFieldValue}'
And         header Content-Type = 'application/json'
And         header Authorization = token
When        method get
Then        status 200

注意:请确保第一个场景中response.objects[0]."name of the field"的取值路径和你实际接口返回的结构匹配,避免取值异常;如果两个场景不在同一个Feature文件中,可以将变量作用域参数改为'suite',就能在整个测试套件范围内共享调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:45:01