A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/WireMock-Net/WireMock.Net/wiki/Response-Templating below:

Response Templating · wiremock/WireMock.Net Wiki · GitHub

Response headers and bodies can optionally be rendered (templated) with:

This enables attributes of the request to be used in generating the response e.g. to pass the value of a request ID header as a response header or render an identifier from part of the URL in the response body. To use this functionality, add .WithTransformer() to the response builder.

1. Define "Handlebars template"
var user = new
{
  firstname = "Stef"
}
C# Example for using Handlebars.Net :
var server = WireMockServer.Start();
server
  .Given(
    Request.Create().WithPath("/some/thing").UsingGet()
  )
  .RespondWith(
    Response.Create()
      .WithBody("Hello world! Your path is {{request.path}}.")
      .WithTransformer()
  );
Mapping Json Example using Handlebars.Net:
{
    "Guid": "fd8ca21b-db82-48bc-ae5a-fc2153c2b0db",
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/bodyasfile_transform123"
                }
            ]
        },
        "Methods": [
            "get"
        ]
    },
    "Response": {
        "Headers": { "Content-Type": "application/xml" },
        "BodyAsFile": "c:\\temp-wiremock\\__admin\\mappings\\_{{request.query.MyUniqueNumber}}_\\MyXmlResponse.xml",
    	"UseTransformer": true,
        "UseTransformerForBodyAsFile": true // ⭐
    }
}

For using Scriban as templating engine, just provide the type:

  // . . .
  .WithTransformer(TransformerType.Scriban) // or TransformerType.ScribanDotLiquid
  // . . .
{
    . . .
    "Response": {
        . . .
    	"UseTransformer": true,
        "TransformerType": "Scriban"
    }
}

Scriban and Handlebars.Net are supported, however some functionality from Scriban cannot not (yet) be used in WireMock.Net, these topics are:

So the examples and explication below is mostly targeted to Handlebars.Net

The model of the request is supplied to the header and body templates. The following request attributes are available:

Transform the content from a referenced file

📝 By default, only the response (headers, statuscode, body) are transformed when the .WithTransformer() or UseTransformer are defined.

⭐ In case you also want to transform the contents from a referenced file (via BodyAsFile), an additional parameter need to added. Like .WithTransformer(bool) or UseTransformerForBodyAsFile = true. (#386 and #1106)

Standard Handlebars helpers

All of the standard helpers (template functions) provided by the C# Handlebars implementation are available.

Additional Handlebars helpers

In addition to the standard helpers, also the helpers from Handlebars.Net.Helpers are supported. The following extra helpers are included in WireMock.Net:

JsonPath support is also present (internal logic is based on Newtonsoft.Json).

Two functions are present:

  1. JsonPath.SelectToken
  2. JsonPath.SelectTokens
This can be used in C# like:
var server = WireMockServer.Start();
server
    .Given(Request.Create().WithPath("/jsonpathtestToken").UsingPost())
    .RespondWith(Response.Create()
        .WithHeader("Content-Type", "application/json")
        .WithBody("{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}")
        .WithTransformer()
    );

⚠️ When returning a more complex Json Body like this:

{
  "market": "{{JsonPath.SelectToken request.bodyAsJson '$.pricingContext.market'}}",
  "languages": "en"
}

You need to to use single quote (') instead of escaped double quotes (\") because of some parsing error @ Handlebars.Net (see also #1108).

Or using the admin mapping file:
{
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/jsonpathtestToken"
                }
            ]
        },
        "Methods": [
            "post"
        ]
    },
    "Response": {
        "Body": "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}",
        "UseTransformer": true,
        "Headers": {
            "Content-Type": "application/json"
        }
    }
}

Note that also replacing values in a Json Object and returning a the body as Json is supported, to use this, use a mapping file like this:

{
  "Request": {
    "Path": {
      "Matchers": [
        {
          "Name": "WildcardMatcher",
          "Pattern": "/test"
        }
      ]
    },
    "Methods": [
      "post"
    ]
  },
  "Response": {
    "BodyAsJson": {
      "path": "{{request.path}}",
      "result": "{{JsonPath.SelectToken request.bodyAsJson \"username\"}}"
    },
    "UseTransformer": true,
    "Headers": {
      "Content-Type": "application/json"
    }
  }
}

It's possible to return random data using the Random Handlebars function.

Example: to generate a random string between 8 and 20 characters, use this code in C#:

var server = WireMockServer.Start();
server
    .Given(Request.Create().WithPath("/random").UsingGet())
    .RespondWith(Response.Create()
        .WithHeader("Content-Type", "application/json")
        .WithBodyAsJson(
            Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
        )
        .WithTransformer()
    );

Example: to generate a random string using a Regex pattern, use this code in C#:

var server = FluentMockServer.Start();
server
    .Given(Request.Create().WithPath("/random-regex").UsingGet())
    .RespondWith(Response.Create()
        .WithHeader("Content-Type", "application/json")
        .WithBodyAsJson(
            Text = "{{Xeger \"[1-9][0-9]{3}[A-Z]{2}\"}",
        )
        .WithTransformer()
    );
Random (all supported randomizers)

You can use the powerful Regular Expression string generator based on Fare - Finite Automata and Regular Expressions.

Besides a random text string, it's also possible to generate this random data:

Note: instead of using \" in above examples, you can also use '.

XPath support is also present

Three functions are present:

  1. XPath.SelectSingleNode
  2. XPath.SelectNodes
  3. XPath.Evaluate

This can be used in C# like:

var server = WireMockServer.Start();
server
    .Given(Request.Create().WithPath("/xpath1").UsingPost())
    .RespondWith(Response.Create()
        .WithHeader("Content-Type", "application/xml")
        .WithBody("<response>{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]\"}}</response>")
        .WithTransformer()
    );

Or using the admin mapping file:

{
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/xpath1"
                }
            ]
        },
        "Methods": [
            "post"
        ]
    },
    "Response": {
        "Body": "<response>{{XPath.SelectSingleNode request.body \"/todo-list/todo-item[1]\"}}</response>",
        "UseTransformer": true,
        "Headers": {
            "Content-Type": "application/xml"
        }
    }
}

For examples on XPath.SelectNodes and XPath.Evaluate, see https://github.com/WireMock-Net/WireMock.Net/blob/master/test/WireMock.Net.Tests/ResponseBuilders/ResponseWithHandlebarsXPathTests.cs


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4