问题
My Karate mock server will accept request in XML form, below is the example of the request:
<methodCall>
<methodName>MyMethod</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>a</name>
<value>abc</value>
</member>
<member>
<name>b</name>
<value><i4>2</i4></value>
</member>
</struct>
</value>
</param>
</params>
Within the <struct>
, it might have multiple <member>
tag. How can I check if within the request <member>
, there is specific <name>
is presented with specific <value>
?
I can define a Scenario
like below:
Scenario: pathMatches('/test') && methodIs('post') && bodyPath('/methodCall/methodName') == 'MyMethod'
to handle the request based on methodName
, but I would like to do different handling depends on what <member>
it contains. For example: If request contains a member with <name>color</name>
with value <value>blue</value>
then I will do the job accordingly.
回答1:
Maybe you are over-thinking this and what you have may be sufficient. All you need to do is return a response
conditionally. One tip is that Karate can auto-covert XML into JSON which is convenient because it is easier to write JSON-path queries or filter operations:
Here is some example code that can give you some ideas:
* def structs = get[0] request..member
* def fun = function(x){ return x.name == 'a' && x.value == 'abc' }
* def test = karate.filter(structs, fun)
* if (test.length) karate.set('response', '<some>response</some>')
I guess the point is you are trying to do non-trivial conditional handling, so the code will be more complex than usual.
You can use JSON-path instead of the karate.filter()
hack, but the query expression may get harder to read IMO. Note that you can define a function such as getStructType()
in the Background
- put all the logic you want in it - and then use it in the Scenario
HTTP path "route" expression.
来源:https://stackoverflow.com/questions/59728792/karate-check-if-xml-request-contains-specific-value