Karate跨Feature文件传递响应属性报错,求解决方案
解决Karate框架跨Feature传递参数的问题
错误原因分析
- 第一个Feature的
Scenario未返回所需变量,调用call时无法捕获注册接口返回的responseId和responseToken - 第二个Feature中
call的传参逻辑错误,此时还未生成responseId变量,无法传递该值 - 请求Payload的赋值格式有误,不能用
* request.userId = {responseId: '#(responseId)'}这种嵌套写法
修正后的代码实现
1. 修正User Registration Feature文件(feature1.feature)
让Scenario返回注册成功后的id和token,供其他Feature调用时获取:
Feature: User Registration Background: * url 'https://test.com' Scenario: Register a New User Given path 'register' And request { "email": "abc123@gmail.com", "password": "Abc123", "firstName": "Abc", "lastName": "API", "gender": "M" } When method post Then status 200 * def responseToken = response.token * def responseId = response.id * print 'Token:', responseToken * print 'User ID:', responseId * return { id: responseId, token: responseToken } // 返回需要传递的变量
2. 修正Validation Feature文件(feature2.feature)
通过call调用第一个Feature并接收返回值,再将id注入到请求Payload中:
Feature: Validation Background: * def registrationResult = call read('feature1.feature') // 调用第一个Feature并接收返回结果 * def responseId = registrationResult.id // 从返回结果中提取userId * url 'https://test.com' Scenario: Send OTP Given path 'sendOTP' * def requestPayload = { "type": "email", "action": "login", "device": "Abc", "userId": responseId // 直接将responseId赋值给请求字段 } And request requestPayload When method post Then status 200
关键说明
- 使用
return关键字让Feature的Scenario返回指定变量,是Karate跨Feature传递参数的标准方式 - 调用
call时接收返回的对象,从中提取所需参数即可直接使用 - 构造请求Payload时,直接将变量赋值给对应字段,无需额外嵌套格式
内容的提问来源于stack exchange,提问作者Noman Ahmed Khan
相关产品推荐
相关产品推荐

