6

I am trying to create a API mock with standalone wiremock. The response body depends upon an attribute in the request body.

With JSON, I was able to do. Here is sample mapping:

{
   "request":{
      "method":"POST",
      "bodyPatterns":[
         {
            "matchesJsonPath":"$.somekey.subkey[?(@.attribute == 'VALUE_123')]"
         }
      ]
   },
   "response":{
      "status":200,
      "bodyFileName":"res.dat",
      "headers":{
         "Content-Type":"application/x-proto;charset=UTF-8"
      }
   }
}

However my main requirement is to deal with google protobuf and I am trying to use text format in lieu of it that mockers will use to mock the API for response. So, the request file is in text format, and does not have any JSON validations like double quotes, or comma at end of each line, etc.

I found that using JSON path, wiremock is unable to match the request body due to its improper format. For example, a request like this:

{
animal {
type {
key1: "value"
key2: value2
}
}
}

instead of

{  
   "animal":{  
      "type":{  
         "key1":"value",
         "key2":"value2"
      }
   }
}

Lets say key1 = value1 should match and response1.json should be returned, or when key1 = someOtherValue, then response2.json should be returned. And yes, key is part of type, and type is part of animal. How can I achieve this request body matching?

xploreraj
  • 3,792
  • 12
  • 33
  • 51

1 Answers1

4

You can just do:

{
  "request": {
  "method": "POST",
    "url": "/authorize/oauth2/token",
    "bodyPatterns": [ {
          "matches": ".username=(test)&."
      }
    ]
  },
  "response": {
    "status": 200,
    . . .

Also https://github.com/tomakehurst/wiremock/issues/575

Stef Heyenrath
  • 9,335
  • 12
  • 66
  • 121
  • 7
    This is one more: `"bodyPatterns" : [ { "contains": "type: CREDIT" } ]` – xploreraj Jan 18 '17 at 05:01
  • This comment helped me. If you have quotes around, you would need to escape them like ```"bodyPatterns" : [ { "contains": "\"type\": \"CREDIT\"" } ]``` – nilesh Mar 05 '21 at 05:30