如何基于标签值运行Karate中多实例的Scenario Outline
Karate Scenario Outline与Zephyr集成:为每个实例匹配对应测试用例标签
问题根源
你的代码中,karate.tagValues.TestCaseKey获取的是整个Scenario Outline的标签集合(T123,T124,T125),无法区分每个Examples实例。afterScenario虽会在每个实例运行后触发,但默认不会自动拆分标签映射到单个实例。
解决方案1:将测试用例Key嵌入Examples表格(推荐)
修改Feature文件,把每个实例对应的Zephyr测试用例Key加到Examples列中,让每个实例运行时携带专属参数:
Scenario Outline: Add two numbers <num1> & <num2> Given I have a calculator When I add <num1> and <num2> Then the result should be <total> Examples: | num1 | num2 | total | testCaseKey | | -2 | 3 | 1 | T123 | | 10 | 15 | 25 | T124 | | 99 | -99 | 0 | T125 |
然后修改afterScenario函数,从场景参数中提取当前实例的测试用例Key:
* configure afterScenario = """ function() { var info = karate.info; // 从当前实例的场景参数中获取对应测试用例Key var testCaseKey = karate.scenarioArgs.testCaseKey; var status = info.errorMessage ? 'Fail' : 'Pass'; karate.call('classpath:Package/Update_Zephyr.feature', { testCaseKey: testCaseKey, statusName: status }); } """
这种方式逻辑直观,实例与标签一一绑定,不会因顺序变动出错。
解决方案2:通过实例索引匹配标签(无需修改Examples表格)
如果不想改动Examples表格,可利用Karate 1.0及以上版本提供的info.scenarioOutlineIndex属性,获取当前实例的索引后,拆分标签数组取对应值:
* configure afterScenario = """ function() { var info = karate.info; // 拆分标签字符串为数组 var testCaseKeys = karate.tagValues.TestCaseKey.split(','); // 获取当前Outline实例的索引(从0开始) var instanceIndex = info.scenarioOutlineIndex; var testCaseKey = testCaseKeys[instanceIndex]; var status = info.errorMessage ? 'Fail' : 'Pass'; karate.call('classpath:Package/Update_Zephyr.feature', { testCaseKey: testCaseKey, statusName: status }); } """
注意:此方法要求标签顺序必须与Examples实例顺序严格对应,一旦调整任意一方的顺序,就会出现匹配错误。
内容的提问来源于stack exchange,提问作者ksl4u
相关产品推荐
相关产品推荐

