[英]MockHttpServletResponse returning empty body for Pageable endpoint
我有以下測試代碼,我正在測試一個可分頁端點,該端點列出了學生的所有條目。
@Autowired
private MockMvc mockMvc;
@MockBean
private StudentRepository studentRepository;
private PageableHandlerMethodArgumentResolver pageableArgumentResolver = new PageableHandlerMethodArgumentResolver();
@BeforeEach
public void init() {
mockMvc = MockMvcBuilders.standaloneSetup(new StudentEndpoint(studentRepository))
.setCustomArgumentResolvers(pageableArgumentResolver)
.build();
}
@Test
@WithMockUser(username = "xx", password = "xx", roles = "USER")
public void whenListStudentUsingCorrectStudentUsernameAndPassword_thenReturnStatusCode200 () throws Exception {
List<Student> students = asList(new Student(1L, "Legolas", "legolas@lotr.com"),
new Student(2L, "Aragorn", "aragorn@lotr.com"));
when(studentRepository.findAll()).thenReturn(students);
mockMvc.perform(get("http://localhost:8080/v1/protected/students/"))
.andExpect(status().isOk())
.andDo(print());
verify(studentRepository, times(1)).findAll();
}
這里的問題是verify(studentRepository, times(1)).findAll();
不起作用,因為 MockHttpServletResponse 正在返回 null 正文。
那是我的終點:
@GetMapping(path = "protected/students")
public ResponseEntity<?> listAll (Pageable pageable) {
return new ResponseEntity<>(studentDAO.findAll(pageable), HttpStatus.OK);
}
還有我的日志:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null Redirected URL = null
Cookies = []
Argument(s) are different! Wanted:
br.com.devdojo.repository.StudentRepository#0 bean.findAll(
);
-> at br.com.devdojo.TestingTestTech.whenListStudentUsingCorrectStudentUsernameAndPassword_thenReturnStatusCode200(TestingTestTech.java:68)
Actual invocations have different arguments:
br.com.devdojo.repository.StudentRepository#0 bean.findAll(
Page request [number: 0, size 20, sort: UNSORTED]
);
有人可以幫助測試可分頁響應的正確方法嗎? 謝謝。
最后,我找到了解決方法。
您只需將 Pageable object 作為參數傳遞給返回 Pageable JSON 的 findAll 方法。
那是我的新工作代碼:
Page<Student> pagedStudents = new PageImpl(students);
when(studentRepository.findAll(isA(Pageable.class))).thenReturn(pagedStudents);
mockMvc.perform(get("http://localhost:8080/v1/protected/students/"))
.andExpect(status().isOk())
.andDo(print());
verify(studentRepository).findAll(isA(Pageable.class));
還有 MockHttpServletResponse:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = {"content":[{"id":1,"name":"Legolas","email":"legolas@lotr.com"},{"id":2,"name":"Aragorn","email":"aragorn@lotr.com"}],"pageable":"INSTANCE","totalElements":2,"totalPages":1,"last":true,"size":2,"number":0,"sort":{"sorted":false,"unsorted":true,"empty":true},"first":true,"numberOfElements":2,"empty":false}
Forwarded URL = null
Redirected URL = null
Cookies = []
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.