【问题标题】:mocking a request with a payload using wiremock使用wiremock模拟带有有效负载的请求
【发布时间】:2023-04-10 22:10:02
【问题描述】:

我目前正在尝试使用 Wiremock 模拟外部服务器。 我的一个外部服务器端点需要一个有效负载。 该端点定义如下:

  def sendRequestToMockServer(payload: String) = {
    for {
      request_entity <- Marshal(payload).to[RequestEntity]
      response <- Http().singleRequest(
          HttpRequest(
            method = HttpMethods.GET,
            uri = "http://localhost:9090/login",
            entity = request_entity
          )
        )
    } yield {
      response
    }
  }

为了使用 Wiremock 模拟这个端点,我编写了以下代码:

    stubFor(
      get(urlEqualTo("/login"))
        .willReturn(
          aResponse()
            .withHeader("Content-Type","application/json")
            .withBodyFile("wireMockResponse.json")
            .withStatus(200)
        )
        .withRequestBody(matchingJsonPath("requestBody.json"))
    )

我在 requestBody.json 文件中定义了请求正文。

但是当我运行测试时,我不断收到一个错误,指出找不到请求的 Url。

我认为错误与withRequestBody(matchingJsonPath("requestBody.json")) 这一行有关,因为当我评论它时,错误消失了。

关于如何解决这个问题的任何建议?

【问题讨论】:

    标签: scala wiremock


    【解决方案1】:

    matchingJsonPath 不会在提供的文件路径中填充文件,而是评估提供的JsonPath。 See documentation.

    我不完全确定是否有办法将请求正文作为 .json 文件提供。如果将文件内容复制到withRequest(equalToJson(_yourJsonHere_)),是否有效?如果是这样,您可以将文件内容作为定义上方的 JSON 字符串获取并将其提供给函数(或者我猜,创建一个函数以从 .json 文件返回 JSON 字符串)。

    此外,您可以创建一个自定义请求匹配器来为您进行解析。我想只有在上述方法不起作用时我才会推荐这个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多