I want to use template response in wiremock and set list as a parameter. How to do that?
I set up wiremock in Java:
wireMockServer.stubFor(get(urlPathEqualTo("/somePath"))
.withQueryParam("place.id", equalTo(buildingId))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile("wiremock/response-template.json") //how to set up this file
.withTransformerParameters(Map.of(
"place", "New York",
"users", List.of(new User("John", 24), new User("Merry", 31)) //list to insert
))
.withTransformers("response-template")));
How to write file: response-template.json to have result like this:
{
"place": "New York",
"users": [
{
"name": "John",
"age": 24
},
{
"name": "Marry",
"age": 31
}
]
}
I know that it should start like this:
{
"place": "{{parameters.place}}",
"users": [
???
]
}
I
CodePudding user response:
The easiest solution would be to use Jackson2 Helper or any other helper that can serialize jsons.
- Add Handlebars jackson2 dependency to your project:
- Gradle
testImplementation 'com.github.jknack:handlebars-jackson2:4.3.0'
- Maven
<!-- https://mvnrepository.com/artifact/com.github.jknack/handlebars-jackson2 -->
<dependency>
<groupId>com.github.jknack</groupId>
<artifactId>handlebars-jackson2</artifactId>
<version>4.3.0</version>
<scope>test</scope>
</dependency>
- Register handler with your wiremock instance :
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort()
.extensions(new ResponseTemplateTransformer(false, "json", Jackson2Helper.INSTANCE)))
The name of the helper will be json
and that is how you will refer to it from your template.
- In your template use it like :
{
"place": "{{parameters.place}}",
"users": {{json parameters.users}}
}
- The output is :
{
"place": "New York",
"users": [{"name":"John","age":24},{"name":"Merry","age":31}]
}
Of course you can customize Jackson2Helper
and create your own instance with own ObjectMapper
instance - this is useful if you are using Spring
and want to use same serialization options everywhere.