unit-testing - 单元测试 StreamingOutput 作为 Responseentity Jersey

标签 unit-testing jar jersey mockito junit4

我正在做类似于中提到的事情 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();

我在这里遗漏了一些非常明显的东西吗?

最佳答案

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

你能做的就是从返回中获取 Response 并调用 Response#getEntity() (返回一个对象)并将其转换为 流输出。然后自己调用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"));

关于unit-testing - 单元测试 StreamingOutput 作为 Responseentity Jersey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37850002/

相关文章:

java - 如何为接口(interface)默认方法编写 Junit

unit-testing - 单元测试时,应该如何处理对象的初始化测试?

java - 如何将 JAR 依赖项包含到 AAR 库中

Jersey - 对预检请求的响应未通过访问控制检查 : No 'Access-Control-Allow-Origin'

java - 使用 Guice AOP 在 Jersey 中进行方法拦截

python - 中断 Python 单元测试时关闭资源

c# - 使用反射获取类构造函数的参数

multithreading - 如何修复 Java 绑定(bind) : UnsatisfiedLinkError?

java-me - 使用 Bouncy CasSTLe 库会导致输出 .jar 文件大小大幅增加

带有 Jersey 的嵌入式tomcat上的java.net.SocketTimeoutException