package de.gedoplan.seminar.sbt.sbtrestexercise; import com.jayway.jsonpath.JsonPath; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc public class Exercise02Test { @Autowired private MockMvc mockMvc; @Test public void testPut() throws Exception { mockMvc.perform(put("/personen/{id}",1) .contentType(MediaType.APPLICATION_JSON) .content(MUSTERMANN_JSON)) .andExpect(status().is(HttpStatus.NO_CONTENT.value())); mockMvc.perform(get("/personen/{id}",1)) .andExpect(jsonPath("$.firstname").value("Maximilian")); } @Test public void testPutNonMatchingId() throws Exception { mockMvc.perform(put("/personen/{id}",2) .contentType(MediaType.APPLICATION_JSON) .content(MUSTERMANN_JSON)) .andExpect(status().is(HttpStatus.BAD_REQUEST.value())); } @Test public void testPutNotFound() throws Exception { mockMvc.perform(put("/personen/{id}",10) .contentType(MediaType.APPLICATION_JSON) .content(MUSTERMANN_ID10_JSON)) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); } @Test public void testDelete() throws Exception { String responseBody = mockMvc.perform(get("/personen")) .andExpect(status().is(HttpStatus.OK.value())).andReturn().getResponse().getContentAsString(); Integer count = JsonPath.read(responseBody,"$.size()"); mockMvc.perform(delete("/personen/{id}",2)) .andExpect(status().is(HttpStatus.OK.value())); mockMvc.perform(get("/personen")) .andExpect(jsonPath("$.size()").value(count-1)); } @Test public void testPost() throws Exception { String location = mockMvc.perform(post("/personen") .contentType(MediaType.APPLICATION_JSON).content( """ { "name": "Test", "firstname": "Test" }""")) .andExpect(status().is(HttpStatus.CREATED.value())) .andReturn().getResponse().getHeader("location"); mockMvc.perform(get(location)) .andExpect(jsonPath("$.name").value("Test")); } private static String MUSTERMANN_JSON = """ { "id": "1", "name": "Mustermann", "firstname": "Maximilian" } """; private static String MUSTERMANN_ID10_JSON = """ { "id": "10", "name": "Mustermann", "firstname": "Maximilian" } """; }