单元测试StreamingOuput作为响应实体Jersey

问题描述 投票:3回答:1

我正在做类似于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();
}

我试图通过模拟像How to get instance of javax.ws.rs.core.UriInfo中提到的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路径切换到其他东西时,我希望能够检查是否出现异常。但是,当我运行/调试测试时,我从未输入

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

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

我错过了一些非常明显的东西吗?

unit-testing jar jersey mockito junit4
1个回答
4
投票

因为直到它击中MessageBodyWriter(这是最终调用StreamingOutput#write的组件)才写入流。

你能做什么,只是从返回中获取Response并调用Response#getEntity()(返回一个Object)并将其转换为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"));
© www.soinside.com 2019 - 2024. All rights reserved.