Spring 模拟测试 return 带有 CompletableFuture 的空主体

Spring Mock Test return null body with CompletableFuture

我正在尝试为我的休息做一些测试api但是当我开始第一个测试时响应主体为空,我认为这是因为我正在使用 CompletableFuture...

@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
public class UserControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    private UserRestController controller;

    @Test
    @WithMockUser(username = "test", password = "test", roles = "ADMIN")
    public void tryGetAllUsers_shouldFindAllUsers() throws Exception {
        mockMvc.perform(get("/api/v1/user/all").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print());
    }
}

控制器class

@GetMapping("/all")
    @RolesAllowed("ADMIN")
    @ResponseBody
    public CompletableFuture<ResponseEntity<Page<User>>> getUsers(@PageableDefault(sort = "id", direction = Sort.Direction.ASC) Pageable pageable) {
        return CompletableFuture.supplyAsync(() -> ResponseEntity.ok(service.getUsers(pageable)));
    }

我试了很多方法,问了很多人,但一个月后我没有找到解决办法...

您可以让 MockMvc 等待您的异步响应。像这样更改代码:

public void tryGetAllUsers_shouldFindAllUsers() throws Exception {
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/user/all")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(request().asyncStarted())
            .andReturn();

    mockMvc
            .perform(asyncDispatch(mvcResult))
            .andExpect(status().isOk())
            .andDo(print());

}