如何在Karate API的Scenario Outline中让指定代码仅执行一次
问题原因
Scenario Outline 内的所有步骤会逐行遍历 Examples 表完整执行,你将 callonce 语句放在了场景步骤内部,因此每一条用例运行时都会重新触发该语句执行。
修复方案
你只需要将文件读取逻辑移到场景外的全局层级即可,整个Feature运行期间只会执行1次读取操作,所有用例复用同一个变量结果,两种实现方式可选:
方式1:直接在Feature顶层定义(最简洁)
Feature: 字段校验测试 # 全局变量定义,整个Feature执行时仅加载一次 * def filePath = callonce read('../path') Scenario Outline: validate all fields Given url Then reqJson.<Request_Value> And request reqJson When method POST Then status 400 Examples: | Request_Value | | filePath.requestValue1 = "value1"| | filePath.requestValue2 = "value2"|
方式2:放在Background块中(适合多个Scenario共享变量的场景)
Feature: 字段校验测试 Background: * def filePath = callonce read('../path') Scenario Outline: validate all fields Given url Then reqJson.<Request_Value> And request reqJson When method POST Then status 400 Examples: | Request_Value | | filePath.requestValue1 = "value1"| | filePath.requestValue2 = "value2"|
内容的提问来源于stack exchange,提问作者Kundan Balse
相关产品推荐
相关产品推荐

