Spring boot 如何创建未发现异常的单元测试?
这里我有一个测试来测试控制器,我成功地测试了create和findByName,我想用findByName\u notFound添加测试,但我还不明白怎么做 这是我的代码:Spring boot 如何创建未发现异常的单元测试?,spring-boot,unit-testing,testing,controller,Spring Boot,Unit Testing,Testing,Controller,这里我有一个测试来测试控制器,我成功地测试了create和findByName,我想用findByName\u notFound添加测试,但我还不明白怎么做 这是我的代码: @Test public void shouldRegisterNewStudent() throws Exception { Student student = new Student(); student.setId(1); student.setParentsName("farizan
@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());
}
}这是一个教程,您可以使用
rest assured
库来测试rest API,它易于使用且功能强大
步骤:
这不是答案;相反,最好是作为OP问题的评论。
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.5</version>
<scope>test</scope>
</dependency>
@LocalServerPort
private int port;
@Test
public void test() {
RestAssured.given()
.port(port)
.get("/test/api") //your endpoint
.then()
.assertThat()
.statusCode(HttpStatus.NOT_FOUND.value());
}
}