为什么空手道配置 headers 与直接在后台设置 headers 的行为不同?

Why does karate configure headers behave differently to setting headers directly in the background?

我编写了一个测试,调用一次 api 端点并在响应中检索一个 etag。之后,我进行了第二次调用,并将 etag 值设置为 if-none-match header。测试如下所示:

Feature: Retrieve station properties

  Background:
    * url baseUrl
    * def contentType = 'application/vnd.whatever'
    * def accessToken = 'ey.foobar.123'
    * configure headers = { Authorization: '#("Bearer " + accessToken)', Accept: '#(contentType)' }

  Scenario: Fetch station properties once and expect a 304 on the sub-sequent request

    Given path '/api/station-properties'
    When method GET
    Then status 200
    And headers {ETag: '#notnull'}
    And def etag = responseHeaders['ETag'][0]

    Given path '/api/station-properties'
    And header If-None-Match = etag
    When method GET
    Then status 304

这基本上可以工作,但我对配置 headers 行不满意,因为我稍后可能会添加其他 headers。因此我考虑使用不同的方法来设置 headers:

Feature: Retrieve station properties

  Background:
    * url baseUrl
    * def contentType = 'application/vnd.whatever'
    * def accessToken = 'ey.foobar.123'
    * header Authorization = 'Bearer ' + accessToken
    * header Accept = contentType

  Scenario: Fetch station properties once and expect a 304 on the sub-sequent request

    Given path '/api/station-properties'
    When method GET
    Then status 200
    And headers {ETag: '#notnull'}
    And def etag = responseHeaders['ETag'][0]

    Given path '/api/station-properties'
    And header If-None-Match = etag
    When method GET
    Then status 304

虽然在这种情况下,headers(授权和接受)在第一次 api 调用时设置,但在第二次调用时它们不是。

为什么会这样?

是的,规则是 configure"persist" for multiple HTTP calls。所以只需在 Background:

中进行此更改
* configure headers = ({ Authorization: 'Bearer ' + accessToken, Accept: contentType })

好吧,是的 - 做你之前做的事。现在应该可以了。