junit 为什么我的控制器返回HTML页面,而不是JSON?

cgfeq70w  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(149)

所以,我有问题,并没有答案.我的休息控制器,返回html页面

@Autowired
        private Gradebook gradebook;        
        
        @GetMapping( value= "/", produces={MediaType.APPLICATION_JSON_VALUE})
        public List<GradebookCollegeStudent> getStudents() {
            gradebook = studentService.getGradebook2();
            return gradebook.getStudents();
        }

我的测试+例外

@Test
    public void getStudentsHttpRequest() throws Exception {
        
        student.setFirstname("Chad");
        student.setLastname("Darby");
        student.setEmailAddress("chad@mail.com");
        entitymanage.persist(student);
        entitymanage.flush();
        
     

mock.perform(MockMvcRequestBuilders.get("/")).andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JSON_UTF8))
    .andExpect(jsonPath("$", hasSize(2)));
            
    //java.lang.AssertionError: Content type expected:<application/json> but was:<text/html;charset=UTF-8>
}

我是怎么解决这个问题的?我在控制器中添加了produces={MediaType.APPLICATION_JSON_VALUE}),我在所有测试之前都设置了MockHttpRespone,但问题还是一样。

response = new MockHttpServletResponse();
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

我也不明白从我的控制器采取index.html页面显示在控制台运行测试后,因为没有一个我的服务不返回索引!

gradebook = studentService.getGradebook2();  
 return gradebook.getStudents();

如果有人知道真实的答案,请帮助!

20jt8wwn

20jt8wwn1#

添加到你的test .header():

mock.perform(MockMvcRequestBuilders.get("/")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE))
                .andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$", hasSize(2)));

相关问题