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

Karate框架调用Feature文件获取Bearer Token返回Null问题排查求助

问题分析与解决

核心原因

你在Token生成Feature中定义的变量名是authToken,但调用时却尝试从返回对象中获取token属性,两者名称不匹配,导致拿到null。

修复方案

方案1:调整Token生成Feature的变量名

修改AuthToken.feature中的变量定义,将authToken改为token,这样调用时就能正确获取:

Given path '/as/token.oauth2'
And header Content-Type = 'application/json'
* params { client_id: 'TestScopeClient', response_type: 'token', grant_type: 'client_credentials',client_secret: '2Federate', scope: 'enr.dipor.enr.r clgn.tdw.clgn.r'}
When method Post
Then status 200
* def token = response  // 变量名改为token

方案2:调用时使用正确的变量名

保持AuthToken.feature不变,调用时通过authToken属性获取返回值:

Scenario: get all users and then get the first user by id
* def t = call read('classpath:ReUsableFunctions/AuthToken.feature') 
* print 'token return value is '+t
* def token = t.authToken  // 使用正确的变量名authToken
* print 'token return value is '+token

优化建议

如果只需要access_token字段,可以直接在Token生成Feature中返回具体值,减少后续处理步骤:

Given path '/as/token.oauth2'
And header Content-Type = 'application/json'
* params { client_id: 'TestScopeClient', response_type: 'token', grant_type: 'client_credentials',client_secret: '2Federate', scope: 'enr.dipor.enr.r clgn.tdw.clgn.r'}
When method Post
Then status 200
* def token = response.access_token

调用时直接拿到access_token字符串:

Scenario: get all users and then get the first user by id
* def token = call read('classpath:ReUsableFunctions/AuthToken.feature') 
* print 'token return value is '+token

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:22:10