首页 > 解决方案 > 如何使用 Wiremock 在字段中返回请求正文作为响应

问题描述

我有一个 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: (

编辑:-

2.19.0我正在使用导致此问题的wiremock版本。我将版本升级到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"
}

标签: wiremockwiremock-standalone

解决方案


使用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"]
  }
}

推荐阅读