package com.example.projectback.controllers; import com.example.projectback.model.Student; import com.example.projectback.repository.StudentRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.context.WebApplicationContext; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; @ExtendWith(SpringExtension.class) @WebMvcTest(StudentController.class) class StudentControllerTest { @MockBean private StudentRepository studentRepository; @Autowired private WebApplicationContext webApplicationContext; @Autowired private MockMvc mvc; @Test void addStudent() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/students").contentType(MediaType.APPLICATION_JSON) .content("{\"firstname\": \"John\", \"lastname\": \"Smith\", \"email\": \"john.smith@example.com\", \"telephone\": \"600345624\"}")).andExpect(MockMvcResultMatchers.status().isCreated()); } @Test void getAllStudents() throws Exception { Student testStudent = new Student(); testStudent.setFirstname("John"); testStudent.setLastname("Smith"); testStudent.setEmail("john.smith@example.com"); testStudent.setTelephone("600345624"); when(studentRepository.findAll()).thenReturn(List.of(testStudent)); RequestBuilder request = MockMvcRequestBuilders.get("/students"); mvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$[0].firstname").value("John")); } }