1

我需要 GET 的网络服务资源:

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 @Path("/status")
 public Response checkNode() {
        boolean status = !NlpHandler.getHandlerQueue().isEmpty();
        status = status || !NlpFeeder.getInstance().getFiles().isEmpty();

        int statusCode = status ? 200 : 420;
        LOG.debug(
            "checking status - status: " + statusCode
            + ", node: " + this.context.getAbsolutePath()
        );

        return Response.status(statusCode).build();
}

关联客户:

public class NodeClient {
    private final Client client;
    private final WebTarget webTarget;

    public NodeClient(String uri) {
        this.uri = "some uri";
        client = ClientBuilder.newCLient();
        webTarget = client.target(uri);

    public synchronized boolean checkNode() throws IOException {
        String path = "status";
        Response response = webTarget
            .path(path)
            .request(MediaType.APPLICATION_JSON)
            .get(Response.class);

        int responseCode = response.getStatus();

        boolean success = responseCode == 200;
        if (!success && responseCode != 420) {
            checkResponse(response);
        }

        return success;
    }
}

在我的测试中,我得到了一个空指针,int responseCode = response.getStatus()我很确定我没有以正确的方式得到响应webTarget。看起来我可以通过 POST 响应正确地做到这一点,但在它期待 GET 时却不行。

    @Test
    public void testCheckNode() throws Exception {
        Response response = Mockito.mock(Response.class);
        Mockito
            .doReturn(response)
            .when(builder)
            .get();

        NodeClient nodeClient;

        Mockito
            .doReturn(200)
            .when(response)
            .getStatus();

        try {
            boolean success = nodeClient.checkNode();

            Assert.assertTrue(success);
        } catch (IOException ex) {
            Assert.fail("No exception should have been thrown");
        }
    }

任何想法为什么我得到一个空响应?

4

1 回答 1

0

我认为我的客户显然很好,测试是错误的。最初我是在嘲笑这个Response班级,现在我发现了它,并让模拟返回了间谍,Response.ok().build())这解决了我的问题。

    @Test
    public void testCheckNode() throws Exception {
        response = Mockito.spy(Response.class);
        Mockito
            .doReturn(Mockito.spy(Response.ok().build()))
            .when(builder)
            .get(Response.class);

        NodeClient nodeClient;
        PowerMockito
            .doNothing()
            .when(nodeClient, "handleResponse", Mockito.any());

        try {
            boolean success = nodeClient.checkNode();

            Assert.assertTrue(success);
        } catch (IOException ex) {
            Assert.fail("No exception should have been thrown");
        }
    }
于 2020-04-01T16:41:06.477 回答