我为我的控制器编写了测试,并且预期的Content-Type有问题。
我的控制器
@RequestMapping(value = "/", method = RequestMethod.GET, produces={"application/json; charset=UTF-8"})
public List<GradebookCollegeStudent> getStudents() {
gradebook = studentService.getGradebook2();
return gradebook.getStudents();
}
就像solve一样,我添加了produces,但没有什么是不变的。
我的测试
@BeforeAll
public static void setup() {
request = new MockHttpServletRequest();
request.setCharacterEncoding("charset=UTF-8");
request.setContentType("application/json");
request.addHeader("Content-Type", APPLICATION_JSON_UTF8);
request.setParameter("firstname", "Chad");
request.setParameter("lastname", "Bronson");
request.setParameter("email_address", "chad@gmail.com");
}
@BeforeEach
public void beforeEach() {
jdbc.execute ("insert into student (id, firstname, lastname, email_address) values ('21', 'Eric', 'Robbys', 'eric@gmail.com')");
jdbc.execute("insert into math_grade (id, student_id, grade) values (21,21,100.00)");
jdbc.execute ("insert into science_grade (id, student_id, grade) values (21,21,100.00)");
jdbc.execute("insert into history_grade (id, student_id, grade) values (21,21,100.00)");
}
@Test
public void getStudentsHttpRequest() throws Exception {
student.setFirstname("Chad");
student.setLastname("Darby");
student.setEmailAddress("chad.darby@luv2code_school.com");
entitymanage.persist(student);
entitymanage.flush();
mock.perform(MockMvcRequestBuilders.get("/")).andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)));
}
像solve一样,我在所有测试之前设置:内容类型,字符编码,添加标题,但什么都没有改变!
我的堆栈跟踪
java.lang.AssertionError: Content type expected:<application/json> but was:<text/html;charset=UTF-8>
在cy控制台中,我可以看到
MockHttpServletRequest:
HTTP Method = GET
Request URI = /
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Language:"en", Content-Type:"text/html;charset=UTF-8"]
Content type = text/html;charset=UTF-8
Body = <!DOCTYPE html>
如何解决这个问题?tnx!
1条答案
按热度按时间4uqofj5v1#
@GetMapping是一个组合注解,用作@RequestMapping(方法= RequestMethod.GET)的快捷方式。
@GetMapping是较新的注解,支持消费
你为什么不直接使用@GetMapping?比如: