automated-testsexpressionkaratedata-driven-tests

Karate: Using data-driven embedded template approach for API testing


I want to write data-driven tests passing dynamic values reading from external file (csv). Able to pass dynamic values from csv for simple strings (account number & affiliate id below). But, using embedded expressions, how can I pass dynamic values from csv file for "DealerReportFormats" json array below?

Any help is highly-appreciated!!

Scenario Outline: Dealer dynamic requests
    Given path '/dealer-reports/retrieval'
    And request read('../DealerTemplate.json')   
  When method POST
    Then status 200
    Examples: 
      | read('../DealerData.csv') | 


DealerTemplate.json is below
{    
  "DealerId": "FIXED",
  "DealerName": "FIXED",
  "DealerType": "FIXED",

  "DealerCredentials": {
    "accountNumber": "#(DealerCredentials_AccountNumber)",
    "affiliateId": "#(DealerCredentials_AffiliateId)"
  },
"DealerReportFormats": [
    {
      "name": "SalesReport",
      "format": "xml"
    },
    {
      "name": "CustomerReport",
      "format": "txt"
    }
  ]
}

DealerData.csv: 

DealerCredentials_AccountNumber,DealerCredentials_AffiliateId
testaccount1,123
testaccount2,12345
testaccount3,123456


Solution

  • CSV is only for "flat" structures, so trying to mix that with JSON is too ambitious in my honest opinion. Please look for another framework if needed :)

    That said I see 2 options:

    a) use proper quoting and escaping in the CSV

    b) refer to JSON files

    Here is an example:

    Scenario Outline:
    * json foo = foo
    * print foo
    
    Examples:
    | read('test.csv') |
    

    And test.csv is:

    foo,bar
    "{ a: 'a1', b: 'b1' }",test1
    "{ a: 'a2', b: 'b2' }",test2
    

    I leave it as an exercise to you if you want to escape double-quotes. It is possible.

    Option (b) is you can refer to stand-alone JSON files and read them:

    foo,bar
    j1.json,test1
    j2.json,test2
    

    And you can do * def foo = read(foo) in your feature.

    You can pass variables from a Scenario Outline into a JSON "template" using embedded expressions. Refer: https://stackoverflow.com/a/47674975/143475