英文:
MockHttpServletResponse returning empty body for Pageable endpoint
问题
我有以下的测试代码,我正在测试一个Pageable端点,用于列出所有学生条目。
@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 返回了一个空的主体。
这是我的端点:
@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]
);
有人可以帮忙指导一下正确的方法来测试可分页的响应吗?谢谢。
英文:
I have the following test code where I'm testing a Pageable endpoint that list all entries for student.
    @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();
}
The problem here is that the  verify(studentRepository, times(1)).findAll(); doesn't work because MockHttpServletResponse is returning a null Body.
Thats my endpoint:
    @GetMapping(path = "protected/students")
public ResponseEntity<?> listAll (Pageable pageable) {
    return new ResponseEntity<>(studentDAO.findAll(pageable), HttpStatus.OK);
}
And my log:
   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]
);    
Could someone please help with the right way to test pageable response? Thanks.
答案1
得分: 1
最终,我找到了如何修复它。
你只需要将一个 Pageable 对象作为参数传递给你的 findAll 方法,该方法返回一个 Pageable JSON。
这是我的新工作代码:
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:
       状态 = 200
    错误消息 = null
      头部 = [Content-Type:"application/json"]
内容类型 = application/json
     主体 = {"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}
转发的 URL = null
重定向的 URL = null
      Cookies = []
英文:
Finally, I found how to fix it.
You just need to pass a Pageable object as parameter to your findAll method that returns a Pageable JSON.
Thats my new working code:
        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));
And the 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 = []
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论