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

Robot Framework调用REST API时如何跨测试用例传递token变量?

问题核心原因

Robot Framework 测试用例内默认创建的变量为局部作用域,仅支持当前用例内部访问,是跨用例传参失败的主要原因,同时你的代码还存在3处疏漏:

  1. Refresh token用例中引用token时错误使用了字典变量引用符&,字符串变量需使用$引用
  2. 未存储Login接口返回的refresh_token值,Refresh token用例中${refresh_token}也会出现未定义报错
  3. 刷新token的请求grant_type参数错误填写为password,刷新场景应为refresh_token

解决步骤

  • 在Login用例中,使用Set Suite Variable关键字将token、refresh_token设置为套件级作用域变量,套件内所有测试用例均可访问
  • 修正Refresh token用例的变量引用语法、grant_type参数值
  • 保持测试用例执行顺序为Login在前、Refresh token在后(Robot Framework 默认按编写顺序执行,无需额外配置)

修改后完整代码

Library     RequestsLibrary
Library     JSONLibrary
Library     OperatingSystem


*** Variable ***
${base_url}       https://api.sportpartnerxxx.vn/v1
${identity_URL}   https://identity.sportpartnerxxx.vn

*** Test Cases ***

Login
    ${body}=    Create Dictionary    client_id=sportpartner-mobile-app    client_secret=ifd-sportpartner-secret-2021-mobile-app    grant_type=password    username=abc    password=123456
    ${header}=  Create Dictionary    Content-Type=application/x-www-form-urlencoded
    ${response}=    Post    ${identity_URL}/connect/token    headers=${header}    data=${body}
    Status Should Be    200
    # 存储token为套件级变量
    ${token}=    Set Variable    Bearer ${response.json()["access_token"]}
    Set Suite Variable    ${token}
    # 存储refresh_token为套件级变量
    ${refresh_token}=    Set Variable    ${response.json()["refresh_token"]}
    Set Suite Variable    ${refresh_token}


Refresh token
    ${body}=    Create Dictionary    client_id=sportpartner-mobile-app    client_secret=ifd-sportpartner-secret-2021-mobile-app    grant_type=refresh_token    refresh_token=${refresh_token}
    ${header}=  Create Dictionary    Content-Type=application/x-www-form-urlencoded    Authorization=${token}
    ${response}=    Post    ${identity_URL}/connect/token    headers=${header}    data=${body}
    Status Should Be    200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:45:03