Java 使用 javax.ws.rs.client 为 inputStream 编写测试

Java write test for inputStream with javax.ws.rs.client

我正在使用 java.ws.rs 进行 GET api,如下所示:

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getMyFile() throws AbsoluteException {
    StreamingOutput outputStream;
    Client client = ClientBuilder.newClient();
    try {
        final InputStream responseStream = client.target(myFileUrl).request().get(InputStream.class);
        outputStream = new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException {
                int length;
                byte[] buffer = new byte[downloadBufferSize];
                while ((length = responseStream.read(buffer)) != -1) {
                    out.write(buffer, 0, length);
                }
                out.flush();
                responseStream.close();
            }
        };
    } catch (Exception ex) {

    }
    return Response
            .ok(outputStream, MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition", "attachment; filename = " + myFile)
            .build();
}

我不知道如何使用 Mockito 或任何其他工具为其编写 unitTest。 我的测试方法如下,但它不起作用:

@Test
public void getMyFile_Success() throws IOException {
    final Client mockClient = Mockito.mock(Client.class);
    final File initialFile = new File("src/test/resources/TestFile.txt");
    final InputStream targetStream =
            new DataInputStream(new FileInputStream(initialFile));
    Mockito.when(mockClient.target("myUrl")
            .request().get(InputStream.class))
            .thenReturn(targetStream);
    Invocation.Builder request = target(CONTEXT_ROOT).request();
    Response response = request.get(Response.class);
    assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
}

我成功地使用了能够模拟构造函数和静态方法的 powermock。 下面是我的代码:

    Client mockClient = Mockito.mock(Client.class); 
    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
        PowerMockito.mockStatic(ClientBuilder.class);
        PowerMockito.when(ClientBuilder.newClient()).thenReturn(this.mockClient);
    }   

    public void getMyFile_Success() throws Exception {
        Invocation.Builder myBuilder = Mockito.mock(Invocation.Builder.class);
        WebTarget webTarget = Mockito.mock(WebTarget.class);
        Mockito.when(mockClient.target(myUrl)).thenReturn(webTarget);
        Mockito.when(webTarget.request()).thenReturn(myBuilder);
        final File initialFile = new File("src/test/resources/TestFile.txt");
        InputStream targetStream =
                new DataInputStream(new FileInputStream(initialFile));
        Mockito.when(myBuilder
                .get(InputStream.class))
                .thenReturn(targetStream);
        Invocation.Builder request = target(CONTEXT_ROOT).request();
        Response response = request.get(Response.class);
        assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
    }