Karate中@report=false场景下karate.prevRequest失效问题
关于@report=false标签下karate.prevRequest获取值为空的问题解答
复现场景
携带@report=false标签运行下述Karate测试场景时,会抛出类型转换错误:
cannot convert, not a json string: [type: NULL, value: null]
测试脚本片段:
@report=false Scenario: POST request; 200 response Given url 'http://localhost:8080' And request { "id": "123" } When method post * def requestBody = karate.prevRequest.body * json requestJson = requestBody
可稳定复现的特征:移除@report=false标签,或是将标签值设置为true后,同一场景可正常捕获请求体,无报错。
结论与原因
该问题不属于操作流程疏漏,是Karate框架针对不同report开关的分支逻辑设计差异导致的:
- 当开启
@report=false时,框架为了降低报告生成阶段的内存开销,会跳过请求、响应快照的完整序列化与存储流程 - 该分支逻辑下,
karate.prevRequest对象的body属性不会被主动填充为实际的请求内容,返回值为null,直接做JSON类型转换就会触发上述报错 - 当
@report设置为true或未启用时,框架会走完整的快照存储流程,karate.prevRequest.body会被正确赋值为传入的请求体内容,因此可以正常完成JSON转换
有效规避方式
如果场景必须开启@report=false以关闭报告生成能力,不要依赖karate.prevRequest快照获取请求体,在定义请求阶段就将请求内容存为独立变量即可完全避开上述逻辑差异:
@report=false Scenario: POST request; 200 response Given url 'http://localhost:8080' * def requestBody = { "id": "123" } And request requestBody When method post * json requestJson = requestBody
内容的提问来源于stack exchange,提问作者Staffier
相关产品推荐
相关产品推荐

