[英]Getting error when testing spring rest async controller
Controller控制器
@PostMapping("/endpoint/group/move")
public DeferredResult<ResponseEntity<List<Endpoint>>> moveEndpointGroup(@RequestBody List<String> EndpointIds,
@RequestParam("from") String fromGroupId, @RequestParam("to") String toGroupId)
throws ResourceNotFoundException, ExecutionException {
DeferredResult<ResponseEntity<List<Endpoint>>> result = new DeferredResult<>();
if (EndpointIds != null && !EndpointIds.isEmpty()) {
CompletableFuture.supplyAsync(() -> EndpointService.moveEndpoints(EndpointIds, fromGroupId, toGroupId), executor)
.whenComplete((movedEndpointsList, ex) -> {
if (ex != null) {
throw new RuntimeException(ex);
}
if (movedEndpointsList.size() == EndpointIds.size()) {
result.setResult(ResponseEntity.status(HttpStatus.OK).body(movedEndpointsList));
} else {
result.setResult(ResponseEntity.status(HttpStatus.PARTIAL_CONTENT).body(movedEndpointsList));
}
});
}
return result;
}
I have written the following test method, it's not working.我已经编写了以下测试方法,它不起作用。 When I run this test I am getting Async result for handler was not set during the specified timeToWait.当我运行此测试时,在指定的 timeToWait 期间未设置处理程序的异步结果。
Can someone help me where I am doing wrong?有人可以帮助我哪里做错了吗?
@Test
public void testMoveEndpointGroup_WhenSuccess() throws Exception {
List<Endpoint> EndpointList = Arrays.asList(Endpoint, Endpoint);
List<String> EndpointIds = Arrays.asList("123");
Mockito.when(EndpointService.moveEndpoints(Mockito.any(), Mockito.anyString(), Mockito.anyString()))
.thenReturn(EndpointList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/endpoint/group/move")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(EndpointIds)).param("from", "gorupA").param("to", "groupB");
MvcResult result = mvc.perform(requestBuilder).andReturn();
result = mvc.perform(MockMvcRequestBuilders.asyncDispatch(result)).andDo(MockMvcResultHandlers.print()).andReturn();
JsonNode actual = objectMapper.readTree(result.getResponse().getContentAsString()).get("content");
String expected = objectMapper.writeValueAsString(Arrays.asList(EndpointList));
Assert.assertEquals(expected, actual.toString());
}
1) You have the controller with url 1)你有带网址的控制器
@PostMapping("/endpoint/group/move")
But in the test you send a request to '/Endpoint s /group/move' (extra s)但是在测试中,您将请求发送到“/Endpoint s /group/move”(额外的)
post("/Endpoints/group/move")
2) And you don't need to '.get("content")' since you have alredy parsed the reponse body. 2) 而且你不需要 '.get("content")' 因为你已经解析了响应体。 Also looks like you don't need to parse the answer to JsonNode, just use a String看起来您也不需要解析 JsonNode 的答案,只需使用 String
String actual = result.getResponse().getContentAsString();
String expected = objectMapper.writeValueAsString(Arrays.asList(EndpointList));
Assert.assertEquals(expected, actual.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.