> moveEndpointGroup(@R-6ren">
gpt4 book ai didi

java - 测试 spring Rest 异步 Controller 时出现错误

转载 作者:行者123 更新时间:2023-12-01 18:31:08 24 4
gpt4 key购买 nike

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;
}

我写了下面的测试方法,它不起作用。当我运行此测试时,我得到了在指定的 timeToWait 期间未设置处理程序的异步结果。

有人可以帮我解决我做错的地方吗?

    @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) 您拥有带有 url 的 Controller

@PostMapping("/endpoint/group/move")

但在测试中,您向“/Endpoints/group/move”发送请求(额外)

post("/Endpoints/group/move")

2) 并且您不需要 '.get("content")' 因为您已经解析了响应主体。看起来你也不需要解析 JsonNode 的答案,只需使用 String

String actual = result.getResponse().getContentAsString();
String expected = objectMapper.writeValueAsString(Arrays.asList(EndpointList));
Assert.assertEquals(expected, actual.toString());

关于java - 测试 spring Rest 异步 Controller 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com