Mirror back http query params in the PACT response json body

94 Views Asked by At

Using PACT how can I mirror back my http query parameters in my http response body? In other words, consider the following http query : /rest/contract?hash=C3459H6S In my PACT response JSON body I want to have {hash : 'C3459H6S' ...omitted code}. The purpose of this is to make PACT responses dynamic rather than static so I won't be delivering the same JSON response for all queries of type /rest/contract?hash=WHATEVERHASHTHATIS

Edit: based on @Matthew Fellows's response and after some research I finished with this code right here :

@Pact(provider = "myProvider", consumer = "myConsumer")
public RequestResponsePact getContractByHash(PactDslWithProvider builder) {
    return builder
        .uponReceiving("a request for a contract by hash")
        .path("/rest/contract")
        .query("hash=${hashPlaceholder}")
        .method("GET")
        .willRespondWith()
        .status(200)
        .headers(Map.of("Content-Type", "application/json"))
        .body("{\"hash\": \"${hashPlaceholder}\"}")
        .toPact();
}

I am getting however this error right here when running my @Test : Pact Test function failed with an exception, possibly due to

Mismatches(mismatches=[PartialMismatch(mismatches=[QueryMismatch(queryParameter=hash, expected=${hashPlaceholder}, actual=C3459H6S, mismatch=Expected '${ hashPlaceholder }' but received C3459H6S for query parameter hash, path= hash)])])
1

There are 1 best solutions below

2
Matthew Fellows On

Can you not do something like this?

      const dynamicBit = '12345678';
      const interaction = {
        uponReceiving: 'a request for a thing',
        withRequest: {
          method: 'GET',
          path: '/rest/contract',
          query: `hash=${dynamicBit}`,
        },
        willRespondWith: {
          status: 200,
          headers: {
            'Content-Type': 'application/json',
          },
          body: {
            hash: dynamicBit 
            /*, ...omitted code*/
          },
        },
      };
      return provider.addInteraction(interaction);

What is the problem you are trying to solve?