MockHttpServletResponse返回空体以用于可分页的终端。

huangapple go评论82阅读模式
英文:

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 = &quot;xx&quot;, password = &quot;xx&quot;, roles = &quot;USER&quot;)
public void whenListStudentUsingCorrectStudentUsernameAndPassword_thenReturnStatusCode200 () throws Exception {
    List&lt;Student&gt; students = asList(new Student(1L, &quot;Legolas&quot;, &quot;legolas@lotr.com&quot;),
            new Student(2L, &quot;Aragorn&quot;, &quot;aragorn@lotr.com&quot;));

    when(studentRepository.findAll()).thenReturn(students);


    mockMvc.perform(get(&quot;http://localhost:8080/v1/protected/students/&quot;))
            .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 = &quot;protected/students&quot;)
public ResponseEntity&lt;?&gt; listAll (Pageable pageable) {
    return new ResponseEntity&lt;&gt;(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(
    
);
-&gt; 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&lt;Student&gt; pagedStudents = new PageImpl(students);

    when(studentRepository.findAll(isA(Pageable.class))).thenReturn(pagedStudents);


    mockMvc.perform(get(&quot;http://localhost:8080/v1/protected/students/&quot;))
            .andExpect(status().isOk())
            .andDo(print());

    verify(studentRepository).findAll(isA(Pageable.class));

And the MockHttpServletResponse:

    MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:&quot;application/json&quot;]
     Content type = application/json
             Body = {&quot;content&quot;:[{&quot;id&quot;:1,&quot;name&quot;:&quot;Legolas&quot;,&quot;email&quot;:&quot;legolas@lotr.com&quot;},{&quot;id&quot;:2,&quot;name&quot;:&quot;Aragorn&quot;,&quot;email&quot;:&quot;aragorn@lotr.com&quot;}],&quot;pageable&quot;:&quot;INSTANCE&quot;,&quot;totalElements&quot;:2,&quot;totalPages&quot;:1,&quot;last&quot;:true,&quot;size&quot;:2,&quot;number&quot;:0,&quot;sort&quot;:{&quot;sorted&quot;:false,&quot;unsorted&quot;:true,&quot;empty&quot;:true},&quot;first&quot;:true,&quot;numberOfElements&quot;:2,&quot;empty&quot;:false}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

huangapple
  • 本文由 发表于 2020年4月10日 21:08:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/61140964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定