[英]Response is NULL when calling response.getStatus, is client not targeting what's in the webservice?
My webservice resource that expects a GET:我需要 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();
}
The associated client:相关客户:
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;
}
}
In my test, I get a nullpointer at int responseCode = response.getStatus()
and I'm fairly sure i'm not getting the response in the right way with webTarget
.在我的测试中,我在
int responseCode = response.getStatus()
得到了一个空指针,我很确定我没有以正确的方式使用webTarget
得到响应。 It looks like i'm able to do so correctly with POST responses but not when it's expecting a GET.看起来我可以通过 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");
}
}
Any ideas why i'm getting a null response?任何想法为什么我得到空响应?
I think my client clode is fine apparently, the test was wrong.我认为我的客户端 clode 显然很好,测试是错误的。 Originally I was mocking the
Response
class, now I spied it instead and made the mock return the spy of Response.ok().build())
and that fixed my problem.最初我是在嘲笑
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.