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

如何在Karate中遍历JSON数组并循环发起API请求?

在Karate中循环数组元素发起API请求的解决方案

Karate提供了两种简洁的方式实现这类需求,以下是具体实现:

方法一:使用karate.forEach()直接遍历数组

这种方式适合在单个场景内快速实现循环逻辑,步骤如下:

  1. 先调用目标接口获取JSON数组,存入变量
  2. 通过karate.forEach()遍历数组,每次取出元素作为路径参数发起请求

示例代码:

Feature: 循环调用详情接口

  Scenario: 获取ID数组并逐个请求详情
    # 获取包含ID的数组(假设接口返回格式为 [1001, 1002, 1003])
    Given url 'https://your-api-domain.com/items'
    When method get
    Then status 200
    * def itemIds = response

    # 遍历数组发起请求
    * karate.forEach(itemIds, function(currentId) {
        Given url 'https://your-api-domain.com/items/' + currentId
        When method get
        Then status 200
        # 可添加断言验证返回结果
        * match response.id == currentId
      })

如果返回的数组是嵌套JSON对象(比如每个元素是{ "itemId": 1001, "name": "test" }),只需调整遍历逻辑:

* karate.forEach(response, function(item) {
    Given url 'https://your-api-domain.com/items/' + item.itemId
    When method get
    Then status 200
  })

方法二:使用场景大纲(Scenario Outline)实现数据驱动测试

这种方式更适合结构化的测试场景,便于维护和扩展:

  1. 先获取数组并转换为场景大纲支持的对象数组格式
  2. 在场景大纲中引用该数组作为数据源

示例代码:

Feature: 数据驱动循环请求详情接口

  Scenario: 获取数据源
    Given url 'https://your-api-domain.com/items'
    When method get
    Then status 200
    # 将数组转换为 { id: xxx } 格式的对象数组
    * def testData = karate.map(response, function(id) { return { id: id } })

  Scenario Outline: 根据ID请求详情
    Given url 'https://your-api-domain.com/items/<id>'
    When method get
    Then status 200
    * match response.id == <id>

    Examples:
      | testData |

内容的提问来源于stack exchange,提问作者Partha2 Mohapatra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:25:07