我正在尝试测试具有 @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);
}
该测试套件带有嘲笑
@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: Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for interface org.springframework.data.domain.Pageable
答案 0 :(得分:0)
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
最诚挚的问候!
答案 1 :(得分:0)
在测试中可分页的页面可能会引起一些麻烦,尤其是当您使用一些额外的工具(如挥舞着的东西或本地数据库)仅用于品尝H2之类的时候。
首先,我们必须添加要测试的控制器:
@Autowired
private TestingController testingController;
不带Pagable的控制器的简单测试如下所示:
given().contentType(ContentType.JSON).log().all().
standaloneSetup(testingController).
body(new RequestObjectExample()).
when().
post("/someUrl?page=0&size=10,asc").
then().statusCode(200);
对于带有Pagable的控制器的简单测试如下所示:
StandaloneMockMvcBuilder standaloneMockMvcBuilder = MockMvcBuilders.standaloneSetup(testingController)
.setCustomArgumentResolvers(pageableArgumentResolver);
given().contentType(ContentType.JSON).log().all().
standaloneSetup(standaloneMockMvcBuilder).
body(new RequestObjectExample()).
when().
post("/someUrl?page=0&size=10,asc").
then().statusCode(200);