Wiremock:如何模拟返回InputStream的终结点?

问题描述

我有一个工作代码,可以请求一个端点并以此方式读取其响应(流是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,len);
      }
    }
  }
  //other stuffs...
}

我尝试使用JUnit4 @Rule在测试环境中使用wiremock模拟这种情况,

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的端点的正确方法

解决方法

花了一些时间阅读Wiremock文档后,我才知道出了什么问题。创建下载某些文件的存根的一种方法是,如果我要使用以下方法,则将该文件放在src/test/resources/__files目录下:

withBodyFile("file.pdf")

默认情况下,这是Wiremock服务器将在其中寻找通过存根下载任何文件的目录。这解决了我的问题。

,

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

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

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

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