Raghunandan J
Raghunandan J

Reputation: 604

Rest API mocking with wiremock : java

This is my utility class to mock the service

public class MockService {


    public static void bootUpMockServices() throws IOException {

        String orderServiceSpecification = readFile("mappings/orderServicesSpecifications.json", Charset.defaultCharset());
        String singleOrder = readFile("mappings/singleOrder.json", Charset.defaultCharset());


        WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/orders"))
                .willReturn(WireMock.aResponse()
                        .withStatus(200)
                        .withBody(orderServiceSpecification)));

        WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/orders/1"))
                .willReturn(WireMock.aResponse()
                        .withStatus(200)
                        .withBody(singleOrder)));

    }

    public static String readFile(String path, Charset encoding) 
            throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }

}

As you can see I'm mocking a GET call /orders (with all the orders) and responding with the body with all the orders kept in a json file.

I'm also calling a single order by GET call /orders/1. I'm responding it with an JSON object in a file. But I want it to be dynamic. Like when I hit it with orders/30 then, I should be dynamically fetch order with id=30 and render it.

Upvotes: 1

Views: 2563

Answers (1)

Tom
Tom

Reputation: 4149

Currently, if you want dynamic behaviour of the kind you described you'll need to write a ResponseDefinitionTransformer and register it with the WireMockServer or WireMockRule on construction.

This is documented here: http://wiremock.org/docs/extending-wiremock/#transforming-responses

Example of a transformer implementation here: https://github.com/tomakehurst/wiremock/blob/master/src/test/java/com/github/tomakehurst/wiremock/ResponseDefinitionTransformerAcceptanceTest.java#L208-L222

What you're trying to do could be done pretty straightforwardly with a stub mapping matching on a URL regex something like /orders/(\d+) and a transformer that parses out the number part then modifies the bodyFileName on the ResponseDefinition.

Upvotes: 1

Related Questions