简体   繁体   中英

How to reuse assertions for scenarios in single feature file using Karate?

I want to assert responseTime of all scenarios. But i do not want to repeat the assertion code in every scenario. Below is my feature file:

Feature: Reqres api test cases

  Background: base url
    Given url base_url

  Scenario: list single user get request
    Given path single_user_path
    When method get
    Then status 200
    And assert responseTime < 4000

Scenario: create user using post and inline json payload
    * def path = '/users'
    Given path path
    And request {"name": "morpheus","job": "leader"}
    When method post
    Then status 201
    And assert responseTime < 4000

In the above code block, I want to avoid responseTime assertion duplication. How to achieve this in karate?. Please help.

No this is not supported and not planned either. It is unlikely every API call will have the exact same SLA. Also this is what the Gatling integration is for: https://stackoverflow.com/a/55146463/143475

EDIT as an example of how you can do "reuse" of response assertions:

Feature:

Background:
* def validateResponse =
"""
function() {
  var contentType = karate.get("responseHeaders['Content-Type'][0]");
  if (contentType !== 'application/json') {
    karate.fail('content type is not json');
  }
  var responseType = karate.get('responseType');
  if (responseType !== 'json') {
    karate.fail('response type is not json');
  }
}
"""

Scenario:
* url 'https://httpbin.org/post'
* request { foo: 'bar' }
* method post
* validateResponse()

Please note that I absolutely don't recommend the above approach because of reasons best explained here: https://stackoverflow.com/a/54126724/143475

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM