Avinash Pagunta
Avinash Pagunta

Reputation: 45

How to construct POJO like for complex request structure using Karate?

I want to construct a complex POJO during run time based on the scenario . In the below sample request structure consider addresses.line1 as mandatory field And I dont have to pass the other fields everytime but need to do on test cases basis.

{
        "site": [{
                "code": "string",
                "mrn": "string"
            }
        ],
        "email": ["string"],
        "addresses": [{
                "line1": "string",
                "line2": "string",
                "city": "string",
                "state": "string",
                "postalCode": "string"
            }
        ],
        "names": [{
                "first": "string",
                "middle": "string",
                "last": "string",
                "suffix": "string"
            }
        ]
    }

Ex: For TestCase#1 I need only below JSON:

{      
        "addresses": [{
                "line1": "string"                 
            }
        ]           
    }

Where as for TestCase#2 I need below JSON

{
        "email": ["string"],
        "addresses": [{
                "line1": "string",
                "line2": "string"
            }
        ],
        "names": [{
                "first": "string",
                "last": "string"
            }
        ]
    }

I referred https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/outline/examples.feature but the example was pretty straight forward with replaceable values.

I was looking for something like @JsonInclude(JsonInclude.Include.NON_DEFAULT)

Upvotes: 1

Views: 643

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58088

Karate is designed to completely avoid POJO-s and give you complete control over creating and modifying complex JSON. So I suggest you temporarily forget about POJO-s and Java, else you won't get the best out of Karate.

There are a few ways to do this, but here is one. First store the complex JSON in a file, called main.json

Then creating the different variants is simple:

Background:
* def main = read('main.json')

Scenario: one
* def payload = karate.filterKeys(main, 'addresses')

Scenario: two
* def payload = main
* remove payload.site

I suggest you read the docs on reading files for more ideas, look out for embedded expressions.

Also see: https://stackoverflow.com/a/51896522/143475

Upvotes: 1

Related Questions