如何在Karate中传递gId_list遍历数组调用批量删除API
Karate脚本遍历数组执行删除API的实现方案
问题描述
现有如下Karate测试脚本:
主脚本代码:* def Test_assignment_type = 'ALL' * def TEST_NODE_ID = '123455667' * def list = [ '123', '1234', '12345' ] * def gId_list = karate.mapWithKey(list, 'HOOK_TEST_LOCATION_GID') * callonce read('classpath:hook/delete-assignments-hook.feature') {HOOK_TEST_LOCATION_ID: "#(TEST_NODE_ID)", HOOK_TEST_ASSIGNMENT_TYPE: "#(Test_assignment_type)"}delete-assignments-hook.feature代码:
* Given path '/nodes/'+HOOK_TEST_LOCATION_ID+'/locations/'+HOOK_TEST_LOCATION_GID+'/assignments' * And param assignmentType = HOOK_TEST_ASSIGNMENT_TYPE * When method delete * Then assert responseStatus == 204 || responseStatus == 404请问如何将gId_list传入delete-assignments-hook.feature,使删除API遍历数组中每个值执行?
解决方案
要实现遍历数组执行删除API,只需修改主脚本的调用逻辑,利用Karate的call指令遍历数组即可,钩子脚本无需改动。
修改后的主脚本代码
* def Test_assignment_type = 'ALL' * def TEST_NODE_ID = '123455667' * def list = [ '123', '1234', '12345' ] * def gId_list = karate.mapWithKey(list, 'HOOK_TEST_LOCATION_GID') // 定义固定参数集合 * def fixedParams = { HOOK_TEST_LOCATION_ID: TEST_NODE_ID, HOOK_TEST_ASSIGNMENT_TYPE: Test_assignment_type } // 合并固定参数与数组元素,遍历调用钩子脚本 * call read('classpath:hook/delete-assignments-hook.feature') karate.map(gId_list, item => karate.merge(fixedParams, item))
钩子脚本保持不变
* Given path '/nodes/'+HOOK_TEST_LOCATION_ID+'/locations/'+HOOK_TEST_LOCATION_GID+'/assignments' * And param assignmentType = HOOK_TEST_ASSIGNMENT_TYPE * When method delete * Then assert responseStatus == 204 || responseStatus == 404
核心逻辑说明
- 用
call替代原有的callonce:callonce仅执行一次钩子脚本,而call在传入数组时会自动遍历每个元素,为每个元素执行一次钩子脚本。 - 参数合并:通过
karate.map和karate.merge,将固定的节点ID、分配类型参数,与数组中每个GID参数合并,确保每次调用钩子脚本时都能拿到完整的参数集合。 - 钩子脚本自动取值:原钩子脚本中的参数引用会自动从每次调用的参数集合中获取对应值,无需额外修改。
内容的提问来源于stack exchange,提问作者harshini reddy
相关产品推荐
相关产品推荐

