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

如何在Karate测试中按指定test_id动态读取外部数据文件?

问题

我有如下Karate测试用例,能不能引用外部数据文件作为Examples表格,而非在每个Scenario中单独定义?

Feature: karate answers 2

Background:
  * url 'http://localhost:8080'

Scenario Outline: given circuit name, validate country
  Given path 'api/f1/circuits/<name>.json'
  When method get
  Then match $.MRData.CircuitTable.Circuits[0].Location.country == '<country>'

  Examples:
    | name   | country  |
    | monza  | Italy    |
    | spa    | Belgium  |
    | sepang | Malaysia |

我了解可以使用动态Scenario Outline,但如果我有如下CSV文件,希望按test_id读取该文件数据,该如何实现?

test_idnamecountry
1monzaItaly
1spaBelgium
2sepangMalaysia

解决方案

完全可以实现,核心思路是先读取CSV文件解析为数据数组,再按指定test_id过滤出目标数据集,最后将过滤后的数据传入动态Scenario Outline批量执行测试。具体步骤如下:

  1. 准备CSV文件
    将表格内容保存为circuits.csv,放在Karate项目的资源目录(如src/test/resources)下,文件内容如下:
test_id,name,country
1,monza,Italy
1,spa,Belgium
2,sepang,Malaysia
  1. 编写动态测试用例
    通过Karate内置函数读取并过滤数据,再调用场景模板批量执行:
Feature: 按test_id读取外部CSV验证赛道国家

Background:
  * url 'http://localhost:8080'

# 定义可复用的测试场景模板
Scenario: 验证赛道对应国家
  Given path 'api/f1/circuits/<name>.json'
  When method get
  Then match $.MRData.CircuitTable.Circuits[0].Location.country == '<country>'

# 执行test_id=1的测试用例
Scenario: 批量运行test_id=1的场景
  * def allData = read('circuits.csv')
  * def targetData = karate.filter(allData, (item) => item.test_id == 1)
  * call read('#this') targetData

# 执行test_id=2的测试用例
Scenario: 批量运行test_id=2的场景
  * def allData = read('circuits.csv')
  * def targetData = karate.filter(allData, (item) => item.test_id == 2)
  * call read('#this') targetData
  1. 灵活扩展:动态指定test_id
    如果需要不修改代码即可切换测试批次,可通过外部参数传入test_id:
Scenario: 动态指定test_id执行
  * def targetId = karate.properties['test.id'] || 1
  * def allData = read('circuits.csv')
  * def targetData = karate.filter(allData, (item) => item.test_id + '' == targetId)
  * call read('#this') targetData

运行时通过命令行传递参数:mvn test -Dtest.id=2


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:22:22