Warm tip: This article is reproduced from serverfault.com, please click

其他-如何使用Wiremock在响应中返回请求正文

(其他 - How to return request body in a field in response using Wiremock)

发布于 2020-12-26 19:55:27

我有一个JSON请求,如下所示:

{
    "fieldOne": 12345,
    "fieldTwo": 1234,
    "fieldThree": "2019-12-05T12:32:42.323905",
    "fieldFour": "string",
    "fieldFive": 5432,
    "fieldSix": "string",
    "fieldSeven": "string",
    "fieldEight": "string"
}

我需要在字段中发送完整的请求JSON对象作为响应。我的Wiremock存根JSON是,

{
  "request": {
    "method": "POST",
    "urlPath": "/endpoint"
},
  "response": {
    "status": 200,
    "jsonBody": {
      "request": "{{{request.body}}}", //If I remove quotes here then I get error so I added the quotes
      "anotherField": "string"
    },
    "headers": {
      "Content-Type": "application/json;charset=UTF-8"
    },
    "transformers": ["response-template"]
  }
}

如何在字段中发送请求正文以作为响应?

我现在得到错误:

    Illegal unquoted character ((CTRL-CHAR, code 10)): 
has to be escaped using backslash to be included in string value\n at [Source: (

编辑:-

我使用的是Wiremock2.19.0版本,这导致了此问题。我将版本升级到2.21.0,现在问题已解决

但是在响应中,我仍然遇到以下问题,其中请求正文在双引号内,这是无效的JSON。回复:-

{
    "request": "{ //Here the double quotes should not be present before curly brace
        "fieldOne": 12345,
        "fieldTwo": 1234,
        "fieldThree": "2019-12-05T12:32:42.323905",
        "fieldFour": "string",
        "fieldFive": 5432,
        "fieldSix": "string",
        "fieldSeven": "string",
        "fieldEight": "string"
    }",
    "anotherField": "string"
}
Questioner
firstpostcommenter
Viewed
0
firstpostcommenter 2020-12-28 17:10:27

使用body代替jsonBody然后,可以使用任何所需的方式来格式化响应消息(正文中双引号中包含的内容)。

这也将适用于wiremock 2.19.0版本

{
  "request": {
    "method": "POST",
    "urlPath": "/endpoint"
},
  "response": {
    "status": 200,
    "body": "{\"request\": {{{request.body}}}, \"anotherField\": \"string\" }",
    "headers": {
      "Content-Type": "application/json;charset=UTF-8"
    },
    "transformers": ["response-template"]
  }
}