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

Karate框架:如何向JSON文件传递变量及解决文件读取失败问题

问题解决:Karate JSON文件读取失败与变量传递

一、文件读取失败的修复

从错误日志可见,系统实际查找的路径是jsonFiles/requests/seugarAuth/authRequest.json,但你在Feature中指定的路径是jsonFiles/requests/authRequest.json,路径不匹配导致文件找不到,按以下步骤处理:

  1. 核对文件实际存放路径

    • 如果JSON文件确实放在seugarAuth子目录下,修正Feature中的读取路径:
      And def requestBody = read('classpath:jsonFiles/requests/seugarAuth/authRequest.json')
      
    • 如果是拼写错误(比如Sugar误写为seugar),统一修正目录名或路径字符串。
  2. 遵循classpath资源规则
    Karate默认从src/test/resources目录加载classpath资源,确保你的JSON文件放在src/test/resources/jsonFiles/requests/(或对应子目录)下。如果文件不在该目录,可移动文件到resources目录,或使用相对路径读取(比如Feature文件在src/test/java/xxx/features/auth/,JSON在src/test/java/xxx/jsonFiles/requests/,则路径为../../jsonFiles/requests/authRequest.json)。

二、JSON变量传递的正确方式

你在JSON模板中使用#(username)和#(password)的语法是合法的,Karate会自动将已定义的变量注入JSON,但需保证变量在读取JSON前定义(你的代码已满足该顺序)。若自动注入失效,可使用以下手动赋值方式:

方式1:用set语法直接修改请求体属性

Scenario: Get Sugar access token
    Given url baseUrl
    And path 'oauth2/token'
    And def username = 'user'
    And def password = 'password'
    And def requestBody = read('classpath:jsonFiles/requests/authRequest.json')
    # 手动替换变量
    And set requestBody.username = username
    And set requestBody.password = password
    When request requestBody
    And method POST
    Then status 200
    * print 'Response: ', response

方式2:直接在Feature中构造请求体(无需单独JSON文件)

如果请求体结构简单,可直接在Feature中定义,规避文件路径问题:

Scenario: Get Sugar access token
    Given url baseUrl
    And path 'oauth2/token'
    And def username = 'user'
    And def password = 'password'
    And request { grant_type: 'password', client_id: 'myClient', username: username, password: password }
    When method POST
    Then status 200
    * print 'Response: ', response

修正后的完整Feature示例(路径正确前提下)

Scenario: Get Sugar access token
    Given url baseUrl
    And path 'oauth2/token'
    And def username = 'user'
    And def password = 'password'
    And def requestBody = read('classpath:jsonFiles/requests/authRequest.json')
    When request requestBody
    And method POST
    Then status 200
    * print 'Response: ', response

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:45:34