Search code examples
wiremockwiremock-standalone

How to use 'wiremock-faker-extension' extension to generate faker stub data when running wiremock as standalone


I would like to use this extension wiremock-faker-extension to generate dynamic stub data and would like to use this faker library for that.

I am running wiremock as standalone service with the command java -jar wiremock-standalone-3.3.1.jar --port 9995 --verbose --global-response-templating

enter image description here

currently I am using another workaround to generate the dynamic data, however I want to switch to faker extension for the same.

Please share your thoughts if you have idea about it.


Solution

  • The wiremock-faker-extension is a great way to generate random data for your stubs. To set it up you need to add the extension to the classpath when you start WireMock.

    If you use the latest version of the faker extension, it should be picked up automatically via the service loader that was added in that release. If you are using an older version of the extension, you will need to load the extension manually. You can do this by adding the --extensions parameter to the command line when you start WireMock. The --extensions parameter is documented on the WireMock docs site here - https://wiremock.org/docs/standalone/java-jar/#command-line-options

    The value of the --extensions parameter should be the fully qualified class name of the extension - org.wiremock.RandomExtension

    You can validate that the extension is loaded by checking the console output when you start WireMock. You should see a line like this:

    extensions: faker-helper,response-template,webhook
    

    Once this is all setup you can use the extension in your stub mappings. Here is an example of a stub mapping that uses the faker extension to generate random data for the response:

    {
      "request": {
        "method": "GET",
        "urlPath": "/faker"
      },
      "response": {
        "status": 200,
        "jsonBody": {
          "name": "{{ random 'Name.fullName' }}",
          "address": "{{ random 'Address.fullAddress' }}"
        },
        "transformers": ["response-template"]
      }
    }
    

    This stub will return a json payload that looks something like this:

    {
      "name": "Mary McKenzie",
      "address": "Suite 140 3883 Mitsuko Skyway, South Shanita, TX 67816"
    }
    

    I have this setup in an example project using docker if you wanted to play around with it. You can find the full example here

    There is a full list of the supported faker methods in the docs directory of the faker extension repository.