4

Hi there I've relativley new to the Wiremock framework. I've got a test enviroment working but I need to for our integration testing need to resolve a dynamic path such as

/test/dynamic/{dynamicpath}/help

where dynamic path is going to be a variable that I want to resolve and then present different data from using a subset of a json file such as

{ dynamicpathA : "hello", dynamicpathB "world" }

at the moment I have :

    stubFor(get(urlPathMatching("/test/dynamic/{dynamicpath}/help"))
            .withHeader("accept", equalTo("application/json"))
            .willReturn(aResponse().withBody(readFile(RESOURCES + "test.json", Charset.defaultCharset()))));

which will return an entire json file with the full subset of data but not the individual components in relation to the dynamic uri. My question is there a way to resolve the dynamic url and return dynamic data from the json?

I hope I'm being specific enough I'll update as need be.

cr0mbly
  • 51
  • 2
  • 4

1 Answers1

0

Totally possible. What you want is a Response Transformer.

You have done the right thing with the path regex matcher which will identify a positive match - that is the end of it's involvement though, the rest is up to the Response Transformer.

You have a couple of options for parsing out the dynamicPath part with Response Transformers, you can either a) supply it as a parameter to the transformer or b) let the Response Transformer evaluate the request URL for the path. Here is an example letting the Response Transformer do all the work.

public static class DynamicTransformer extends ResponseDefinitionTransformer {

    @Override
    public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) {
          String path = request.getUrl();
          String dynamicPath = ...;     // Pull out the dynamic part
          String transformedJson = ...; // Render the JSON string applicable 
          return new ResponseDefinitionBuilder()
                .withHeader("Content-Type", "application/json")
                .withStatus(200)
                .withBody(transformedJson)
                .build();
    } 

    @Override
    public String name() {
        return "dynamic-transformer";
    }      

So then your test looks like

WireMockServer wireMock = new WireMockServer(wireMockConfig()
     .extensions(new DynamicTransformer()));

stubFor(get(urlPathMatching("/test/dynamic/[^/]+/help"))
    .withHeader("accept", equalTo("application/json"))
    .willReturn(aResponse()
    .withTransformers("dynamic-transformer")));
markdsievers
  • 7,151
  • 11
  • 51
  • 83