【问题标题】:Wiremock: how to mock endpoint that returns InputStream?Wiremock:如何模拟返回 InputStream 的端点?
【发布时间】:2020-10-19 15:37:18
【问题描述】:

我有一个请求端点并以这种方式读取其响应的工作代码(流是 PDF):

private Response readResponseBody(Response response) throws IOException {
  InputStream inputStream = response.readEntity(InputStream.class);
  try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
    if (inputStream != null) {
      byte[] buffer = new byte[1024];
      int len;
      while ((len = inputStream.read(buffer)) != -1) { //error this line with wiremock
        os.write(buffer, 0, len);
      }
    }
  }
  //other stuffs...
}

我尝试在使用 JUnit4 @Rule 的测试环境中使用 wiremock 来模拟那个 enpoint,这样:

byte[] pdfFile = Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("file.pdf").toURI()));
stubFor(
  get(urlPathMatching(mockPath))
  .withHeader("Authorization", equalTo(mockedToken))
  .willReturn(aResponse()
    .withStatus(200)
    .withBody(pdfFile)));

但是当我请求模拟端点时,我无法读取 InputStream,我在上面提到的行中收到此错误:

org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected

哪种方法是模拟使用 Wiremock 返回 InputStream 的端点的正确方法?

【问题讨论】:

    标签: java rest inputstream junit4 wiremock


    【解决方案1】:

    花了一些时间阅读 Wiremock 文档后,我发现了问题所在。创建一个下载一些文件的存根的一种方法是将该文件放在src/test/resources/__files 目录下,如果我要使用该方法:

    withBodyFile("file.pdf")
    

    默认情况下,这是 Wiremock 服务器通过存根获取要下载的任何文件的目录。这解决了我的问题。

    【讨论】:

      【解决方案2】:

      基于this response,我猜您可以将文件路径作为响应正文返回。

        .willReturn(aResponse()
          .withStatus(200)
          .withBodyFile("/path/to/pdf/file")));
      

      如果这不起作用,我建议在响应中添加内容类型标头。假设文件是​​pdf,那将是

      .withHeader("Content-Type", "application/pdf")
      

      【讨论】:

      • 我试过你的方法。现在错误已经改变。我得到: javax.ws.rs.ProcessingException: org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 2674; received: 0 ... and wiremock return status 500! 我测试了给定的路径与 File.exists()
      • 我怀疑路径不是任意的或绝对的,但必须是src/test/resources/__files相对路径@
      • 此外,您可以使用此处列出的方法更改 WireMock 查找文件的位置:wiremock.org/docs/configuration/#file-locations
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2016-12-19
      • 1970-01-01
      相关资源
      最近更新 更多