空手道API测试-在同一功能文件的不同场景中重用变量 [英] Karate API Testing - Reusing variables in different scenarios in the same feature file

查看:68
本文介绍了空手道API测试-在同一功能文件的不同场景中重用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

空手道是否支持一项功能,您可以在此场景中定义变量,并在同一功能文件中的其他场景中重用该变量.我尝试做同样的事情,但收到错误消息.在同一功能文件中重用变量的最佳方法是什么?

Does Karate supports a feature where you can define a variable in a scenario and reuse it in other scenarios in the same feature file. I tried doing the same but get an error. What's the best way to reuse the variables within the same feature file ?

Scenario: Get the request Id
    * url baseUrl
    Given path 'eam'
    When method get
    Then status 200
    And def reqId = response.teams[0]resourceRequestId

Scenario: Use the above generated Id
   * url baseUrl
   * print 'From the previous Scenario: ' + reqId

错误:

Caused by: javax.script.ScriptException: ReferenceError: "reqId" is not defined in <eval> at line number 1

推荐答案

使用Background:部分.这是一个示例.

对于每种情况,对于Background:中的变量,将被重新初始化,这是标准测试框架的设置"行为.如果您希望初始化仅发生一次,则可以使用挂钩,例如callonce .

the variable if in the Background: will be re-initialized for every scenario which is standard testing framework "set up" behavior. You can use hooks such as callonce - if you want the initialization to happen only once.

如果您试图在一种情况下修改变量,并期望在下一个Scenario开始时它现在具有修改后的值,则您会误解了Scenario的概念.只需将您的步骤组合到一个Scenario中,因为考虑一下:这就是您要测试的"流程".

If you are trying to modify a variable in one scenario and expect it to be now having that modified value when the next Scenario starts, you have misunderstood the concept of a Scenario. Just combine your steps into one Scenario, because think about it: that is the "flow" you are trying to test.

每个Scenario应该能够独立运行 .将来Scenario -s的执行顺序甚至可以是随机的,也可以并行运行.

Each Scenario should be able to run stand-alone. In the future the execution order of Scenario-s could even be random or run in parallel.

另一种解释方式是-如果您注释掉一个Scenario其他人应该继续工作.

Another way to explain this is - if you comment out one Scenario other ones should continue to work.

请不要将Scenario视为记录"测试重要部分的一种方式.您可以始终使用注释(例如# foo bar).一些团队认为每个HTTP端点"应位于单独的Scenario中-绝对不建议这样做.查看 Hello World示例本身,它故意显示2个调用,一个POSTGET

Please don't think of the Scenario as a way to "document" the important parts of your test. You can always use comments (e.g. # foo bar). Some teams assume that each HTTP "end point" should live in a separate Scenario - but this is absolutely not recommended. Look at the Hello World example itself, it deliberately shows 2 calls, a POST and a GET !

您可以使用 call 轻松地重用代码,因此您不必担心关于代码复制是否会成为问题.

You can easily re-use code using call so you should not be worrying about whether code-duplication will be an issue.

此外-如果可以使流程更易于阅读,则可以进行一些代码重复.有关详细信息,请参见此答案-并阅读

Also - it is fine to have some code duplication, if it makes the flow easier to read. See this answer for details - and also read this article by Google.

这篇关于空手道API测试-在同一功能文件的不同场景中重用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆