Karate mock - how to match against request body content

霸气de小男生 提交于 2021-02-05 07:52:06

问题


With Karate, I'm trying to work out how to return different mock responses based on the content of the request body.

I've got

Feature: ...
Scenario: pathMatches('/users/login') && methodIs('post') && request == {"username": "gooduser", "password": "goodpassword"}
  * def responseStatus = 200
  * def response = {"status: login ok"}
Scenario: pathMatches('/users/login') && methodIs('post') && request == {"username": "baduser", "password": "badpassword"}
  * def responseStatus = 401
  * def response = {"status: login not ok"}
Scenario:
  * print request
  * print requestHeaders

When I send a request with either the "gooduser" or "baduser" details, they're falling through to the default scenario. This prints the request, which looks like I'd expect.

For example, if I run

curl -X POST -d '{"username":"baduser","password":"badpassword"}' http://localhost:8999/users/login

I can see in the Karate logs that the first 2 scenarios are being skipped and the match is on (empty). However, the logs are also printing out the request body which looks correct, so I'm surprised the 2nd scenario isn't matching the request I'm sending.

Also, if I remove the '&& request = {...}' clause from the scenario, the match works fine.

Feels like I'm missing something obvious - can anyone please point me in the right direction?


回答1:


Yes, the == sign won't work for complex objects (in any language), which is why the match syntax of Karate is such a big deal. Keep in mind that the Scenario expression is evaluated as pure JavaScript.

EDIT: for you the simplest option, is to just use the request object directly. Since it is JSON in your case, a simple JS expression like request.username == 'gooduser' will work !

For those who use XML, there are some Karate functions that will do what you need. bodyPath() is what will also work for you. And it is better to make the decision based on one or two values in the payload, not the whole thing, and this is what real servers do anyways:

Scenario: pathMatches('/users/login') && methodIs('post') && bodyPath('$.username') == 'gooduser'

You can use karate.match(request, json) also, but it won't be as elegant.

And as I initially mentioned in the comment, you could move the logic of deciding what to respond with into the body of the Scenario, something like this:

* def response = request.username == 'gooduser' ? read('good.json') : read('bad.json')


来源:https://stackoverflow.com/questions/57457297/karate-mock-how-to-match-against-request-body-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!