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

如何使用karate.exec执行curl命令并解析响应做断言?

Karate测试示例:使用karate.exec调用curl并断言

以下是符合要求的Karate脚本,仅通过karate.exec执行curl命令、解析响应并完成断言,不使用常规的GIVEN-WHEN-THEN场景:

// 定义curl命令,单引号包裹避免内部双引号转义问题
def curlCommand = 'curl --header "router-destination-service-name: localService" --header "router-destination-service-namespace: local" -X GET "localhost:9876/echo1?zzz=123&aaa=123&yyy=123&bbb=123&xxx=123&ccc=123&www=123"'

// 执行curl命令,获取标准输出
def curlResponse = karate.exec(curlCommand).stdout

// 将JSON格式的输出解析为可操作的对象
def responseObject = karate.fromString(curlResponse)

// 执行各项断言
assert responseObject.serverHostname == 'localService'
// 注意:原响应中字段拼写为reqeustMethod(缺少字母u),若为笔误请自行修正字段名
assert responseObject.reqeustMethod == 'GET'
assert responseObject.requestUri == '/echo1?zzz=123&aaa=123&yyy=123&bbb=123&xxx=123&ccc=123&www=123'
assert responseObject.requestParams.zzz[0] == '123'
assert responseObject.requestHeaders.accept[0] == '*/*'

关键说明:

  • 使用单引号包裹curl命令,避免内部双引号需要转义的麻烦
  • karate.exec()返回的对象包含stdout属性,对应curl命令的输出内容
  • karate.fromString()将JSON字符串转换为Karate可直接操作的对象,方便提取属性和断言
  • 断言直接使用assert关键字完成,无需依赖Gherkin语法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:13:13