karate

How to save a list of responses from a API in a Scenario Outline and verify if they exist in a Database table?


I have karate feature file as stated below. Whenever I POST a request in this API, it generates a response like this "ABCDEF356-FGHFH56-46DVDG-EGR654". I have Scenario Outline as stated below where it executes multiple times with different sets of data. Every time , it executes , different response with unique ID like above needs to be capture. I am able to connect to SQL server but how do I verify if that each ID we captured is present in the Table or not? my responseMessages does not print all the responses it captured.it prints only 1 response .how do I do it and validate it with the query. Select * from test where id = response[0] , response[1] etc

Background:

 * url APIurl
  * def config = { username: '',password:'',url:'jdbc:sqlserver://:1433;databaseName=',driverClassName:'com.microsoft.sqlserver.jdbc.SQLServerDriver'}
  * def DbUtils = Java.type('com.testI.DbUtils')
  * def db = new DbUtils(config)
  * def responseMessages = []      
                                                                                    Scenario Outline : Transmit a valid message with various version numbers via POST method successfully and capture the success response
    Given request ("abcdef <version>")
    When method POST
    Then status 200
    And print response
    And print version
    And def responseMessage = response
    And karate.appendTo(responseMessages, responseMessage)
    * karate.forEach(responseMessages, function(response){ karate.log(response) })


    Examples:
      | version|
      | 2.1    |
      | 2.2    |

Solution

  • I would not recommend a Scenario Outline, if you want to do something at the end of the "loop". Refer this pattern in the documentation: https://github.com/karatelabs/karate#data-driven-features

    Here is an example you can try locally and please study it carefully:

    Feature:
    
    Scenario:
    * def data = [{ id: 1 }, { id: 2 }, { id: 3 }]
    * def result = call read('@called') data
    * def names = result.map(x => x.response.name)
    * match names == ['Leanne Graham', 'Ervin Howell', 'Clementine Bauch']
    
    @called @ignore
    Scenario:
    * url 'https://jsonplaceholder.typicode.com/users'
    * path id
    * method get
    

    Note how we "collected" the response from each iteration in the loop and did a match on just the name.