Karate API Testing - Reusing variables in different scenarios in the same feature file

我是研究僧i 提交于 2019-11-28 09:05:56

问题


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

Error:

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

回答1:


Use a Background: section. Here is an example.

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

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.

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.

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

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).

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



来源:https://stackoverflow.com/questions/46079130/karate-api-testing-reusing-variables-in-different-scenarios-in-the-same-featur

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!