如何使用空手道工具和功能文件比较2个包含数组的JSON对象

时间:2019-01-10 10:09:57

标签: api testing karate

场景文件

  • 所有文件都在同一目录中。

title-update-request.json

{id: 12, name: 'Old Hello', config:[{username: 'qwe', password: 'tyu'},{username: 'abc', password: 'xyz'}]}

title-update-response.json

{id: 12, name: 'New Hello', config:[{username: 'qwe', password: 'tyu'},{username: 'abc', password: 'xyz'}]}

title-update-error-request.json

{id: 00, name: 'Old Hello', config:[{username: 'qwe', password: 'tyu'},{username: 'abc', password: 'xyz'}]}

title-update-error-response.json

{Error: 'not found', Message: 'The provided Book is not found.'}

book-record.feature

Feature: CRUD operation on the book records.

Background:
        * def signIn = call read('classpath:login.feature')
        * def accessToken = signIn.accessToken
        * url baseUrl

 Scenario: Change title of book in the single book-record.
    * json ExpResObject = read('classpath:/book-records/title-update-response.json')
    * json ReqObject = read('classpath:/book-records/title-update-request.json')
    * call read('classpath:/book-records/update.feature') { Token: #(accessToken), ReqObj: #(ReqObject), ResObj: #(ExpResObject), StatusCode: 200 }

  Scenario: Change title of book in the non-existing book-record.
    * json ExpResObject = read('classpath:/book-records/title-update-error-request.json')
    * json ReqObject = read('classpath:/book-records/title-update-error-response.json')
    * call read('classpath:/book-records/update.feature') { Token: #(accessToken), ReqObj: #(ReqObject), ResObj: #(ExpResObject), StatusCode: 400 }

update.feature

功能:更新记录。

Scenario: Update single book-record.
    Given path '/book-record'
    And header Authorization = 'Bearer ' + __arg.Token
    And header Content-Type = 'application/json'
    And request __arg.ReqObj
    When method put
    Then status __arg.StatusCode
    And response == __arg.ExpectedResponse

场景1的实际API响应是:

{name: 'New Hello', config:[{username: 'abc', password: 'xyz'},{username: 'qwe', password: 'tyu'}]}

场景2的实际API响应是:

 {Error: 'not found', Message: 'The provided Book is not found.'}

问题:我应该如何验证update.feature文件中的响应,因为问题是如果我使用#^^ config进行更改,而该方法不适用于方案:2和response == _arg .ExpectedResponse在场景1中不起作用?

1 个答案:

答案 0 :(得分:2)

这是经典的测试过度设计。如果有人告诉您测试需要“重用”,请不要听那个人的话。

您有两种情况,一种是幸福的道路,另一种是负面的道路。我正在提供您如何在下面编写否定路径,其余的取决于您。

Scenario: Change title of book in the non-existing book-record.
Given path '/book-record'
And header Authorization = 'Bearer ' + accessToken
And request {id: 00, name: 'Old Hello', config:[{username: 'qwe', password: 'tyu'},{username: 'abc', password: 'xyz'}]}
When method put
Then status 400
And response == {Error: 'not found', Message: 'The provided Book is not found.'} 

看看它有多干净?无需在测试中“极端”重复使用。如果您仍然坚持要一个能够处理所有极端情况的超通用可重用功能文件,那只会给自己造成麻烦。看看您现有的测试变得多么不可读!!