调用 response.getStatus 时响应为 NULL,客户端是否不针对 Web 服务中的内容?



我的Web服务资源需要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()处得到了一个null指针,我很确定我没有用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");
}
}

你知道我为什么会得到无效的回复吗?

我认为我的客户端clode显然很好,测试是错误的。最初我是在嘲笑Response类,现在我监视它,并使mock返回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");
}
}

相关内容

最新更新