返回PagedResources的单元测试Spring MVC控制器

返回PagedResources的单元测试Spring MVC控制器,第1张

返回PagedResources的单元测试Spring MVC控制器

我通过从Controller构造函数中删除Pageable
pageable来解决它,因为我还是不需要它。然后,PagedResourcesAssembler汇编程序引发了错误

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.web.PagedResourcesAssembler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.data.web.PagedResourcesAssembler.<init>()

我深入研究了ResourceAssembler的主题,并提出了以下解决方案:

控制器:

@RequestMapping(method=RequestMethod.GET)public ResponseEntity<PagedResources<AccountResource>> getAccounts(        @RequestParam(value="name", required = false) String name,         @RequestParam(value="username", required = false) String username,         @RequestParam(value="email", required = false) String email,         @RequestParam(value="lastName", required = false) String lastName,        @RequestParam(value="size", required = true, defaultValue = "10") Integer size,        @RequestParam(value="page", required = true, defaultValue = "0") int page,        @RequestParam(value="sort", required = false, defaultValue = "username") String sort,        @RequestParam(value="direction", required = false, defaultValue = "asc") String direction,        UriComponentsBuilder uriBuilder,        HttpServletRequest request,         HttpServletResponse response) {    // Build page request    AccountList list = null;    Page<Account> resultPage = null;    Direction sortDirection = Direction.ASC;    if(direction.equals("desc")) {        sortDirection = Direction.DESC;    }    PageRequest pReq = new PageRequest(page, size, sortDirection, sort);    resultPage = accountService.findAll(pReq);    HateoasPageableHandlerMethodArgumentResolver resolver = new HateoasPageableHandlerMethodArgumentResolver();    PagedResourcesAssembler<Account> accountPageAssembler = new PagedResourcesAssembler<Account>(resolver, null);    return new ResponseEntity<PagedResources<AccountResource>>(accountPageAssembler.toResource(resultPage, new AccountResourceAsm()), HttpStatus.OK);}

我在这里使用HateoasPageableHandlerMethodArgumentResolver创建资源汇编程序,以将Page转换为要返回的PagedResource。

然后,我终于可以成功运行控制器测试(如问题所示)。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5153682.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存