mardi 14 juillet 2020

how can i create unit test with not found exception?

here i have a test to test the controller, i was succes to test create and findByName succesfully, and i want to add test with findByName_notFound but i don't understand yet to make it.

here my code :

@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());
}

}

Aucun commentaire:

Enregistrer un commentaire