Karate框架如何按条件为被调用的feature传递全局请求头
问题原因
你遇到的配置不传递问题是Karate的默认上下文隔离规则导致的:
- 全局
karate-config.js的配置只会在每个feature初始化时继承一次,如果任意被调用的子feature内执行了configure headers = {}全量重置头配置,就会覆盖继承的全局头,所以会出现只有第一个请求带自定义头的情况。 - 主feature内的
configure headers默认仅作用于当前feature的直接请求,call调用的子feature默认启用独立配置空间,不会自动继承父feature的头配置。
可行解决方案
方案1:调用子feature时启用shared: true参数(推荐,无需修改公共库代码)
在所有call公共feature的语句后添加shared: true参数,即可让子feature完全继承父级的所有配置(包括头、全局变量等),无需修改公共库代码。
修改后的调用示例:
Background: * configure headers = { Authorization: #(getToken), 'Datasource-Type': 'test' } // 所有call语句增加shared: true参数 * def getToken = call read('classpath:com/commons/karate/token-service.feature') { shared: true } * def createSmth = call read('classpath:com/commons/karate/createSmth.feature') { shared: true } * def accId = createSmth.accId * def id = createSmth.id Scenario: Do Smth // 原本需要传自定义参数的调用,把shared加在参数列表里即可 * def createSmthElse = call read('classpath:com/commons/karate/createSmthElse.feature') { Token: #(token), shared: true } * call read('classpath:com/commons/karate/putSmth.feature') { shared: true } * def createSmthElseAnother = call read('classpath:com/commons/karate/createSmthElseAnother.feature') { shared: true } Given url featureService And path '/.../details/employeeSorting' And request {} When method post Then status 200
方案2:全局开启call配置共享(适合全项目同场景统一配置)
如果当前项目所有测试场景都需要携带这个头,不想每个call语句都加参数,可以直接在karate-config.js中添加全局配置,让所有call调用默认继承父上下文:
karate.configure('headers', { 'Datasource-Type': 'test' }); // 新增这一行,全局开启call配置共享 karate.configure('call', { shared: true });
方案3:公共库兼容动态头变量(适合公共库迭代优化)
如果可以迭代公共库代码,可以把Datasource-Type定义为可空变量,公共feature的头配置引用该变量,Karate会自动忽略值为null的头:
- 在
karate-config.js中定义变量:
// 需要该头的场景设为'test',不需要的场景设为null即可 var datasourceType = 'test';
- 所有公共feature的头配置采用追加方式,避免全量覆盖:
// 不要用configure headers = {}全量覆盖,用header命令追加 * header Datasource-Type = #(datasourceType)
注意事项
如果公共feature内存在configure headers = {}全量重置头的逻辑,父级传递的头会被直接覆盖,需要把这类逻辑修改为用header命令追加指定头,避免覆盖全局配置。
内容的提问来源于stack exchange,提问作者Belinka_23
相关产品推荐
相关产品推荐

