3

I am using wiremock to mock http server and I am returning responses from json files (using withBodyFile method).

Now I want to choose and return response json file based on request parameter. For the example below, I want to define one stub so that the body file is chosen based on request parameter.

myMockServer.stubFor(
       get(urlEqualTo(myEndPoint+ "?key=key1"))
       .willReturn(aResponse().withStatus(200)
       .withHeader("Content-Type", "application/json")
       .withBodyFile("response_key1.json")

myMockServer.stubFor(
       get(urlEqualTo(myEndPoint+ "?key=key2"))
       .willReturn(aResponse().withStatus(200)
       .withHeader("Content-Type", "application/json")
       .withBodyFile("response_key2.json")
myMockServer.stubFor(
       get(urlEqualTo(myEndPoint+ "?key=key3"))
       .willReturn(aResponse().withStatus(200)
       .withHeader("Content-Type", "application/json")
       .withBodyFile("response_key3.json")

Any idea how this would be possible? I tried defining transformer but it was not possible to get Stream Source Path from Response object in overridden method so can't use that appraoch. Thanks a lot..

Kumar Gaurav
  • 729
  • 3
  • 9
  • 21

2 Answers2

1

Body File name can't be parameterized in wiremock as of now. I had a similar requirement, I needed to return the file based on the request URL. So I implemented a transformer as below:

public class BodyFileNameResponseTransformer extends ResponseDefinitionTransformer {


public ResponseDefinition transform(Request request, ResponseDefinition rd,
    FileSource fileSource, Parameters parameters) {

    if (rd.getBodyFileName().startsWith("{{")) {
        return new ResponseDefinitionBuilder().**withBodyFile**(request.getUrl().substring(1))
            .withStatus(rd.getStatus())
            .withHeaders(rd.getHeaders())
            .withTransformers(
                rd.getTransformers().toArray(new String[rd.getTransformers().size()]))
            .build();
    }

    return rd;
}

public String getName() {
    return "BodyFileNameTransformer";
}

}

you can use request.queryParameter(key) instead of request.getUrl() and form any file path. Create the file path based on your need and set it as bodyFile on returned ResponseDefinition.

Don't forget to start wiremock with --extensions: Extension class names

More details at Extending Wiremock

Abhinav Agarwal
  • 224
  • 1
  • 5
1

This is possible by using the inbuilt template helpers provided by Handlebar.

myMockServer.stubFor(
       get(urlEqualTo(myEndPoint+ "?key=key3"))
       .willReturn(aResponse().withStatus(200)
       .withHeader("Content-Type", "application/json")
       .withBodyFile("response_{{request.query.key}}.json")

Check for the various models available at http://wiremock.org/docs/response-templating/.

Purus
  • 5,701
  • 9
  • 50
  • 89