单元测试 StreamingOutput 作为 Responseentity Jersey

Unit Testing StreamingOuput as Response entity Jersey

我正在做类似于中提到的事情 Example of using StreamingOutput as Response entity in Jersey

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response streamExample(@Context UriInfo uriInfo) {
  StreamingOutput stream = new StreamingOutput() {
    @Override
    public void write(OutputStream os) throws IOException,WebApplicationException {
    try{
      Writer writer = new BufferedWriter(new OutputStreamWriter(os));
      //Read resource from jar
      InputStream inputStream = getClass().getClassLoader().getResourceAsStream("public/" + uriInfo.getPath());

      ...//manipulate the inputstream and build string with StringBuilder here//.......
      String inputData = builder.toString();
      Writer writer = new BufferedWriter(new OutputStreamWriter(os));
      writer.write(inputData);
      writer.flush();
    } catch (ExceptionE1) {
        throw new WebApplicationException();
      }
    }
};
  return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();
}

我正在尝试通过模拟

中提到的 URIInfo 来对此进行单元测试
  public void testStreamExample() throws IOException, URISyntaxException {
        UriInfo mockUriInfo = mock(UriInfo.class);
        Mockito.when(mockUriInfo.getPath()).thenReturn("unusal-path");
        Response response = myresource.streamExample(mockUriInfo);}

我希望能够检查当我将 jar 的路径切换到某个东西时是否出现异常 else.But,当我 run/debug 测试时,我从未输入

public void write(OutputStream os) throws IOException,
            WebApplicationException {...}

部分,我总是只点击 return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();

我是不是漏掉了一些很明显的东西??

因为流在到达 MessageBodyWriter 之前不会被写入(这是最终调用 StreamingOutput#write 的组件)。

你能做的就是从 return 中获取 Response 并调用 Response#getEntity() (return 是一个对象)并将其转换为 StreamingOutput。然后自己调用 write 方法,传递一个 OutputStream,也许是一个 ByteArrayOutputStream,这样你就可以将内容作为 byte[] 来检查它。这一切看起来像

UriInfo mockInfo = mockUriInfo();
Response response = resource.streamExample(mockInfo);
StreamingOutput output = (StreamingOutput) response.getEntity();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
output.write(baos);
byte[] data = baos.toByteArray();
String s = new String(data, StandardCharsets.UTF_8);
assertThat(s, is("SomeCharacterData"));