spring – 使用PageableDefault测试rest控制器

我试图测试一个具有@getmapping一个参数和PageableDefault的休息服务

   @GetMapping(path = "/api/{serial}/gender")
    public ResponseEntity<?> task(
        @PathVariable(value = "serial") String Serial,
        @PageableDefault(size = 5, value = 0) Pageable pageable) {
    return ResponseEntity.ok(page);
}

测试套件与mockmvc

@Test
public void testTask() throws Exception {
 String url ="/api/123456789/gender";
    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url))
           .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
}

我收到以下错误,我无法注入Pageable导致其接口
我怎么能模拟@pageable默认值?

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是java.lang.IllegalStateException:找不到接口org.springframework.data.domain.Pageable的主要或默认构造函数

解决方法:

Guilhermo,

试试这段代码:

mockMvc = MockMvcBuilders.standaloneSetup(controller)
   .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
   .setViewResolvers(new ViewResolver() {
       @Override
       public View resolveViewName(String viewName, Locale locale) throws Exception {
          return new MappingJackson2JsonView();
      }
   })
   .build();

有关详细信息,请参阅此帖子:Isolated Controller Test can’t instantiate Pageable

最好的祝福!

上一篇:Spring Boot中的WebMvcTest


下一篇:Codeforces555 B. Case of Fugitive