如何运行带多参数的Karate测试?添加参数表后测试失效
解决Karate测试参数化运行问题
你的问题出在仅定义了参数表却没有触发遍历执行,Karate不会自动遍历table的每一行,需要用正确的数据驱动写法来实现多参数测试。下面给两种可行的解决方案:
方案1:使用Scenario Outline + Examples(推荐)
这是Karate最常用的数据驱动写法,直接把参数放到Examples中,Scenario Outline会自动遍历每一行执行:
@tag1 Scenario Outline: Business User Sign Up Given header Content-Type = applicationJsonHeader When url identitySignUpUrl And header Authorization = auth * def requestBody = read('classpath:resources/test.json') * replace requestBody.userName = userNameInput * replace requestBody.phoneNumber = phoneNumberInput * replace requestBody.country = '<region>' And request requestBody When method POST Then status 200 * def errors = response.errors And match errors == '#null' * print response Examples: | region | | 'USA' | | 'CAN' | # 可以添加更多地区参数
方案2:在Scenario中用forEach遍历table
如果想保留原Scenario结构,可通过karate.forEach循环遍历table的每一行,手动执行测试逻辑:
@tag1 Scenario: Business User Sign Up * table regions | region | | 'USA' | | 'CAN' | * karate.forEach(regions, function(row){ Given header Content-Type = applicationJsonHeader When url identitySignUpUrl And header Authorization = auth * def requestBody = read('classpath:resources/test.json') * replace requestBody.userName = userNameInput * replace requestBody.phoneNumber = phoneNumberInput * replace requestBody.country = row.region And request requestBody When method POST Then status 200 * def errors = response.errors And match errors == '#null' * print response })
为什么原代码失效?
你之前的写法仅定义了regions table变量,但没有告诉Karate要遍历每一行执行测试逻辑,导致#(region)无法找到对应变量,替换失败。改用上面两种写法后,参数会被正确注入到测试流程中。
内容的提问来源于stack exchange,提问作者mattsmith5
相关产品推荐
相关产品推荐

