Over a million developers have joined DZone.

Wiremock and Response Transformer

DZone 's Guide to

Wiremock and Response Transformer

This article will help you learn about Wiremock's Response Transformer and how to hook it into your tests and use it to modify responses.

· DevOps Zone ·
Free Resource

I wanted to test a scenario where:

  • For the first x calls, respond with y
  • Then, for x+1, respond with z

Wiremock by itself doesn't provide a direct way to stub different responses akin to Mockito's thenReturn or Spock's multiple stubs. Wiremock, however, provides a ResponseTransformer. I used Wiremock's ResponseTransformer to store state, and return y by default but return z on x+1 try.

  static class SuccessfulAtLastTransformer extends ` {

        int count = 1

        SuccessfulAtLastTransformer() {}

        ResponseDefinition transform(
                final Request request, final ResponseDefinition responseDefinition, final FileSource fileSource) {

            if (request.getUrl().contains("/customer/cust1234")) {
                if (count == 3) {
                    def responseJson = new JsonSlurper().parseText(responseDefinition.body)
                    // Set the customerId on the final try
                    responseJson.customerCar = "toyota"
                    def newRequestBody = JsonOutput.toJson(responseJson)
                    return new ResponseDefinitionBuilder()

                return new ResponseDefinitionBuilder()
                        .withHeader("COUNT", count++ as String)

            return responseDefinition

        boolean applyGlobally() {
            return false

        String name() {
            return "SuccessfulAtLastTransformer"

Line #1: extend import com.github.tomakehurst.wiremock.extension.ResponseTransformer

Line #8: Override the transform function.

Line #11: Check if this is the API you are interested in.

Line #12: Check if the count has reached a certain threshold, and if so, then add customerCar property to response JSON.

Line #23: Add count to the response header. That acts as our state storage. Once the count will reach x in this case 3, then change the response (line #13).

Line #34: Set apply globally false, i.e. don't use this ResponseTransformer as an interceptor anywhere else but where I put it.

Line #40: Give your transformer a name.

Once you have defined a ResponseTransformer like above, you can then attach it to the Wiremock instance, like so:

def customerServiceMock =  


Please let me know if you have any questions or if there's a better way to do the same thing in Wiremock via comments on this post.

wiremock ,devops ,testing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}