【发布时间】:2020-07-15 03:10:48
【问题描述】:
这里我有一个测试来测试控制器,我成功地测试了 create 和 findByName,我想用 findByName_notFound 添加测试,但我还不明白怎么做。
这是我的代码:
@Test
public void shouldRegisterNewStudent() throws Exception {
Student student = new Student();
student.setId(1);
student.setParentsName("farizan");
student.setParentsMobile("8465");
student.setName("sahru");
student.setClassroom(null);
student.setNote("free text");
Mockito.when(studentService.save(student)).thenReturn(student);
mockMvc.perform(post("/register")
.contentType("application/json")
.content(objectMapper.writeValueAsString(student)))
.andExpect(status().isCreated());
}
@Test
public void findStudentByName()throws Exception{
Student student = new Student();
student.setId(1);
student.setParentsName("farizan");
student.setParentsMobile("8465");
student.setName("sahru");
student.setClassroom(null);
student.setNote("free text");
final String name = "sahru";
given(studentService.findByName("sahru")).willReturn(student);
mockMvc.perform(get("/findByName/{name}",name)
.contentType("application/json")
.content(objectMapper.writeValueAsString(student)))
.andExpect(status().isOk());
}
@Test
public void findStudentByName_notFound()throws Exception{
final String name = "sahru";
given(studentService.findByName("sarah")).willReturn((Student) Collections.emptyList());
mockMvc.perform(get("/findByName/{name}",name)
.contentType("application/json"))
.andExpect(status().isNotFound());
}
}
【问题讨论】:
标签: spring-boot unit-testing testing controller