[英]Response is NULL when calling response.getStatus, is client not targeting what's in the webservice?
我需要 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");
}
}
任何想法為什么我得到空響應?
我認為我的客戶端 clode 顯然很好,測試是錯誤的。 最初我是在嘲笑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.