0
votes

I'm working with two microservices using Spring Cloud Contract. One providing its contract, and the other one consuming it. In one scenario the provider response is the same that the request.

So the provider contract is like this:

  Contract.make {
  request {
    method 'POST'
    url '/provider/foo'
    body(
        "foo": $(regex("[a-zA-Z0-9]{20}"))          
    )
  }
  response {
    status 200
    body(
        "fooResponse": fromRequest().body("\$.foo")
    )
 }

And the generated wiremock mapping:

{
  "id" : "a80c0871-f4c0-49e3-8cc1-94de39899669",
  "request" : {
    "url" : "/provider/foo",
    "method" : "POST",
    "bodyPatterns" : [ {
      "matchesJsonPath" : "$[?(@.['foo'] =~ /[a-zA-Z0-9]{20}/)]"
    } ]
  },
  "response" : {
    "status" : 200,
    "body" : "{\"fooResponse\":\"{{{jsonpath this '$.foo'}}}\"}",
    "transformers" : [ "response-template" ]
  },
  "uuid" : "a80c0871-f4c0-49e3-8cc1-94de39899669",
  "scenarioName" : "scenarioReturnSameAsRequest",
  "requiredScenarioState" : "Started"
}

But when my code calls to the provider, with foo as any text, the wiremock returns:

{
    "fooResponse" : "{{{jsonpath this '$.foo'}}}"
}

How can I build a contract that responses the same parameters as the request body?


Edit

I tried with a fixed value on the response and works fine:

  Contract.make {
  request {
    method 'POST'
    url '/provider/foo'
    body(
        "foo": $(regex("[a-zA-Z0-9]{20}"))          
    )
  }
  response {
    status 200
    body(
        "fooResponse": "fooValue"
    )
 }

Now wiremock return:

{
    "fooResponse" : "fooValue"
}

Maybe is not supported getting from request a regex value?

2

2 Answers

0
votes

I think the mapping should contain request.body instead of this. Also I wonder if you need to use 3 times a { or just 2 times. Or do you need to escape these?

Possible mapping:

"response" : {
  "status" : 200,
  "body" : "{\"fooResponse\":\"{{jsonpath request.body '$.foo'}}\"}",
  "transformers" : [ "response-template" ]
},

See also the chapter JSONPath helper on http://wiremock.org/docs/response-templating

0
votes

I had the same problem once. You can try to use value() like this:

"fooResponse": value(fromRequest().body('$.foo'))