Request body matching in WireMock (not JSON/XML)

37.2k views Asked by At

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?

1

There are 1 answers

2
Stef Heyenrath On BEST ANSWER

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