При вызове response.getStatus ответ равен NULL. Разве клиент не нацелен на то, что находится в веб-сервисе? - PullRequest
1 голос
/ 01 апреля 2020

Мой ресурс веб-сервиса, который ожидает 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");
        }
    }

Есть идеи, почему я получаю нулевой ответ?

1 Ответ

0 голосов
/ 01 апреля 2020

Я думаю, что с моим клиентом все в порядке, видимо, тест был неверным. Первоначально я издевался над классом 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");
        }
    }
...