问题
JSON Response
{
Feed[
{"item_type":"cycle","id":123},
{"item_type":"computer","name":"mac"},
{"item_type":"Bag","weight":"2"}
]
}
As nested schema is changing based on item type
so can we compare schema based on item type?
example: if item_type is cycle then it should compare with id,
if item_type is computer then it should compare name like this
I have tried with below:
* def schema = {item_type:"#string",id:'##number',name: '##string',weight:'##string'}
in this schema validation even item_type is cycle and name is mac, test cases will pass but in actual it should fail
回答1:
First let me recommend that trying to do these extreme "generic" validations may be a waste of time. See this answer: https://stackoverflow.com/a/54126724/143475
But here is one possible solution, there could be other ways.
Please read the docs and research other answers to understand this properly. This uses a second feature file.
First feature file:
* def response =
"""
[
{ "item_type": "cycle", "id": 123 },
{ "item_type": "computer", "name": "mac" },
{ "item_type": "bag", "weight": "2" }
]
"""
* print response
* def data =
"""
{
cycle: { id: '#number' },
computer: { name: '#string' },
bag: { weight: '#string' }
}
"""
* def isValid = function(x){ karate.call('called.feature', x) }
* karate.forEach(response, isValid)
Second feature file (called called.feature
):
@ignore
Feature:
Scenario:
* def expected = data[__arg.item_type]
* match __arg contains expected
来源:https://stackoverflow.com/questions/57899242/nested-json-response-validation