From 9cfd80c6d8c22f8534571526c39b4ef5b77fe378 Mon Sep 17 00:00:00 2001 From: Dave Syer Date: Thu, 27 Jul 2023 16:19:07 +0000 Subject: [PATCH] Update Spring Boot --- pom.xml | 12 +- .../owner/FormWidgetControllerAdvice.java | 14 +- .../samples/petclinic/owner/Owner.java | 11 +- .../petclinic/owner/OwnerController.java | 6 +- .../samples/petclinic/vet/VetController.java | 6 +- .../petclinic/owner/OwnerControllerTests.java | 145 ++++++++++-------- .../petclinic/owner/PetControllerTests.java | 54 ++++--- .../petclinic/owner/VisitControllerTests.java | 18 ++- .../CrashControllerIntegrationTests.java | 98 ++++++++++++ .../system/CrashControllerTests.java | 28 ++-- .../petclinic/vet/VetControllerTests.java | 10 +- 11 files changed, 278 insertions(+), 124 deletions(-) create mode 100644 src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java diff --git a/pom.xml b/pom.xml index 3f79515..1af1a77 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ org.springframework.boot spring-boot-starter-parent - 3.0.2 + 3.1.2 petclinic @@ -28,7 +28,7 @@ 0.8.7 v8.11.1 0.0.10 - 0.0.31 + 0.0.39 @@ -70,8 +70,8 @@ runtime - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime @@ -182,8 +182,8 @@ ${project.build.sourceEncoding} ${project.reporting.outputEncoding} - ${maven.compiler.source} - ${maven.compiler.target} + ${java.version} + ${java.version} diff --git a/src/main/java/org/springframework/samples/petclinic/owner/FormWidgetControllerAdvice.java b/src/main/java/org/springframework/samples/petclinic/owner/FormWidgetControllerAdvice.java index 4154276..9626021 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/FormWidgetControllerAdvice.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/FormWidgetControllerAdvice.java @@ -138,8 +138,11 @@ public InputField(String label, String name, String type, BindingResult status) put("name", name); if (status != null) { put("valid", !status.hasFieldErrors(name)); - put("errors", status.getFieldErrors(name).stream().map(error -> error.getDefaultMessage()) - .collect(Collectors.toList())); + put("errors", + status.getFieldErrors(name) + .stream() + .map(error -> error.getDefaultMessage()) + .collect(Collectors.toList())); put("value", status.getFieldValue(name) == null ? "" : status.getFieldValue(name).toString()); } else { @@ -158,8 +161,11 @@ public SelectField(String label, String name, List values, BindingResult String value; if (status != null) { put("valid", !status.hasFieldErrors(name)); - put("errors", status.getFieldErrors(name).stream().map(error -> error.getDefaultMessage()) - .collect(Collectors.toList())); + put("errors", + status.getFieldErrors(name) + .stream() + .map(error -> error.getDefaultMessage()) + .collect(Collectors.toList())); value = status.getFieldValue(name) == null ? "" : status.getFieldValue(name).toString(); } else { diff --git a/src/main/java/org/springframework/samples/petclinic/owner/Owner.java b/src/main/java/org/springframework/samples/petclinic/owner/Owner.java index 9f5411e..6f9043a 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/Owner.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/Owner.java @@ -143,9 +143,14 @@ public Pet getPet(String name, boolean ignoreNew) { public String toString() { return new ToStringCreator(this) - .append("id", this.getId()).append("new", this.isNew()).append("lastName", this.getLastName()) - .append("firstName", this.getFirstName()).append("address", this.address).append("city", this.city) - .append("telephone", this.telephone).toString(); + .append("id", this.getId()) + .append("new", this.isNew()) + .append("lastName", this.getLastName()) + .append("firstName", this.getFirstName()) + .append("address", this.address) + .append("city", this.city) + .append("telephone", this.telephone) + .toString(); } } diff --git a/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java b/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java index c688690..958a1cb 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/OwnerController.java @@ -122,8 +122,10 @@ private String addPaginationModel(int page, Model model, String lastName, Page pagemodel(value, page)).collect(Collectors.toList())); + model.addAttribute("pages", + IntStream.range(1, paginated.getTotalPages() + 1) + .mapToObj(value -> pagemodel(value, page)) + .collect(Collectors.toList())); model.addAttribute("hasPages", paginated.getTotalPages() > 1); model.addAttribute("totalPages", paginated.getTotalPages()); model.addAttribute("listOwners", listOwners); diff --git a/src/main/java/org/springframework/samples/petclinic/vet/VetController.java b/src/main/java/org/springframework/samples/petclinic/vet/VetController.java index ffe3868..b85e332 100644 --- a/src/main/java/org/springframework/samples/petclinic/vet/VetController.java +++ b/src/main/java/org/springframework/samples/petclinic/vet/VetController.java @@ -61,8 +61,10 @@ private String addPaginationModel(int page, Page paginated, Model model) { model.addAttribute("last", page == paginated.getTotalPages()); model.addAttribute("previous", page - 1); model.addAttribute("next", page + 1); - model.addAttribute("pages", IntStream.range(1, paginated.getTotalPages() + 1) - .mapToObj(value -> pagemodel(value, page)).collect(Collectors.toList())); + model.addAttribute("pages", + IntStream.range(1, paginated.getTotalPages() + 1) + .mapToObj(value -> pagemodel(value, page)) + .collect(Collectors.toList())); model.addAttribute("hasPages", paginated.getTotalPages() > 1); model.addAttribute("totalPages", paginated.getTotalPages()); return "vets/vetList"; diff --git a/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java b/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java index 5fdd2f7..cc126dd 100644 --- a/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/owner/OwnerControllerTests.java @@ -94,7 +94,7 @@ void setup() { george.setPetsInternal(Collections.singleton(max)); given(this.owners.findByLastName(eq("Franklin"), any(Pageable.class))) - .willReturn(new PageImpl(Lists.newArrayList(george))); + .willReturn(new PageImpl(Lists.newArrayList(george))); given(this.owners.findAll(any(Pageable.class))).willReturn(new PageImpl(Lists.newArrayList(george))); @@ -107,31 +107,40 @@ void setup() { @Test void testInitCreationForm() throws Exception { - mockMvc.perform(get("/owners/new")).andExpect(status().isOk()).andExpect(model().attributeExists("owner")) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); + mockMvc.perform(get("/owners/new")) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("owner")) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); } @Test void testProcessCreationFormSuccess() throws Exception { - mockMvc.perform(post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs") - .param("address", "123 Caramel Street").param("city", "London").param("telephone", "01316761638")) - .andExpect(status().is3xxRedirection()); + mockMvc + .perform(post("/owners/new").param("firstName", "Joe") + .param("lastName", "Bloggs") + .param("address", "123 Caramel Street") + .param("city", "London") + .param("telephone", "01316761638")) + .andExpect(status().is3xxRedirection()); } @Test void testProcessCreationFormHasErrors() throws Exception { - mockMvc.perform( - post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs").param("city", "London")) - .andExpect(status().isOk()).andExpect(model().attributeHasErrors("owner")) - .andExpect(model().attributeHasFieldErrors("owner", "address")) - .andExpect(model().attributeHasFieldErrors("owner", "telephone")) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); + mockMvc + .perform(post("/owners/new").param("firstName", "Joe").param("lastName", "Bloggs").param("city", "London")) + .andExpect(status().isOk()) + .andExpect(model().attributeHasErrors("owner")) + .andExpect(model().attributeHasFieldErrors("owner", "address")) + .andExpect(model().attributeHasFieldErrors("owner", "telephone")) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); } @Test void testInitFindForm() throws Exception { - mockMvc.perform(get("/owners/find")).andExpect(status().isOk()).andExpect(model().attributeExists("owner")) - .andExpect(view().name("owners/findOwners")); + mockMvc.perform(get("/owners/find")) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("owner")) + .andExpect(view().name("owners/findOwners")); } @Test @@ -150,78 +159,90 @@ void testProcessFindFormSuccess() throws Exception { void testProcessFindFormByLastName() throws Exception { Page tasks = new PageImpl(Lists.newArrayList(george)); Mockito.when(this.owners.findByLastName(eq("Franklin"), any(Pageable.class))).thenReturn(tasks); - mockMvc.perform(get("/owners?page=1").param("lastName", "Franklin")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID)); + mockMvc.perform(get("/owners?page=1").param("lastName", "Franklin")) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID)); } @Test void testProcessFindFormNoOwnersFound() throws Exception { Page tasks = new PageImpl(Lists.newArrayList()); Mockito.when(this.owners.findByLastName(eq("Unknown Surname"), any(Pageable.class))).thenReturn(tasks); - mockMvc.perform(get("/owners?page=1").param("lastName", "Unknown Surname")).andExpect(status().isOk()) - .andExpect(model().attributeHasFieldErrors("owner", "lastName")) - .andExpect(model().attributeHasFieldErrorCode("owner", "lastName", "notFound")) - .andExpect(view().name("owners/findOwners")); + mockMvc.perform(get("/owners?page=1").param("lastName", "Unknown Surname")) + .andExpect(status().isOk()) + .andExpect(model().attributeHasFieldErrors("owner", "lastName")) + .andExpect(model().attributeHasFieldErrorCode("owner", "lastName", "notFound")) + .andExpect(view().name("owners/findOwners")); } @Test void testInitUpdateOwnerForm() throws Exception { - mockMvc.perform(get("/owners/{ownerId}/edit", TEST_OWNER_ID)).andExpect(status().isOk()) - .andExpect(model().attributeExists("owner")) - .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) - .andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) - .andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St.")))) - .andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) - .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); + mockMvc.perform(get("/owners/{ownerId}/edit", TEST_OWNER_ID)) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("owner")) + .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) + .andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) + .andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St.")))) + .andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) + .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); } @Test void testProcessUpdateOwnerFormSuccess() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") - .param("lastName", "Bloggs").param("address", "123 Caramel Street").param("city", "London") - .param("telephone", "01616291589")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); + mockMvc + .perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") + .param("lastName", "Bloggs") + .param("address", "123 Caramel Street") + .param("city", "London") + .param("telephone", "01616291589")) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); } @Test void testProcessUpdateOwnerFormHasErrors() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") - .param("lastName", "Bloggs").param("city", "London")).andExpect(status().isOk()) - .andExpect(model().attributeHasErrors("owner")) - .andExpect(model().attributeHasFieldErrors("owner", "address")) - .andExpect(model().attributeHasFieldErrors("owner", "telephone")) - .andExpect(view().name("owners/createOrUpdateOwnerForm")); + mockMvc + .perform(post("/owners/{ownerId}/edit", TEST_OWNER_ID).param("firstName", "Joe") + .param("lastName", "Bloggs") + .param("city", "London")) + .andExpect(status().isOk()) + .andExpect(model().attributeHasErrors("owner")) + .andExpect(model().attributeHasFieldErrors("owner", "address")) + .andExpect(model().attributeHasFieldErrors("owner", "telephone")) + .andExpect(view().name("owners/createOrUpdateOwnerForm")); } @Test void testShowOwner() throws Exception { - mockMvc.perform(get("/owners/{ownerId}", TEST_OWNER_ID)).andExpect(status().isOk()) - .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) - .andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) - .andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St.")))) - .andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) - .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) - .andExpect(model().attribute("owner", hasProperty("pets", not(empty())))) - .andExpect(model().attribute("owner", hasProperty("pets", new BaseMatcher>() { - - @Override - public boolean matches(Object item) { - @SuppressWarnings("unchecked") - List pets = (List) item; - Pet pet = pets.get(0); - if (pet.getVisits().isEmpty()) { - return false; - } - return true; + mockMvc.perform(get("/owners/{ownerId}", TEST_OWNER_ID)) + .andExpect(status().isOk()) + .andExpect(model().attribute("owner", hasProperty("lastName", is("Franklin")))) + .andExpect(model().attribute("owner", hasProperty("firstName", is("George")))) + .andExpect(model().attribute("owner", hasProperty("address", is("110 W. Liberty St.")))) + .andExpect(model().attribute("owner", hasProperty("city", is("Madison")))) + .andExpect(model().attribute("owner", hasProperty("telephone", is("6085551023")))) + .andExpect(model().attribute("owner", hasProperty("pets", not(empty())))) + .andExpect(model().attribute("owner", hasProperty("pets", new BaseMatcher>() { + + @Override + public boolean matches(Object item) { + @SuppressWarnings("unchecked") + List pets = (List) item; + Pet pet = pets.get(0); + if (pet.getVisits().isEmpty()) { + return false; } - - @Override - public void describeTo(Description description) { - description.appendText("Max did not have any visits"); - } - }))).andExpect(view().name("owners/ownerDetails")); + return true; + } + + @Override + public void describeTo(Description description) { + description.appendText("Max did not have any visits"); + } + }))) + .andExpect(view().name("owners/ownerDetails")); } } diff --git a/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java b/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java index f8a802f..8833ad3 100755 --- a/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/owner/PetControllerTests.java @@ -71,46 +71,62 @@ void setup() { @Test void testInitCreationForm() throws Exception { - mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdatePetForm")).andExpect(model().attributeExists("pet")); + mockMvc.perform(get("/owners/{ownerId}/pets/new", TEST_OWNER_ID)) + .andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdatePetForm")) + .andExpect(model().attributeExists("pet")); } @Test void testProcessCreationFormSuccess() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") - .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); + mockMvc + .perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") + .param("type", "hamster") + .param("birthDate", "2015-02-12")) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); } @Test void testProcessCreationFormHasErrors() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty").param("birthDate", - "2015-02-12")).andExpect(model().attributeHasNoErrors("owner")) - .andExpect(model().attributeHasErrors("pet")).andExpect(model().attributeHasFieldErrors("pet", "type")) - .andExpect(model().attributeHasFieldErrorCode("pet", "type", "required")).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdatePetForm")); + mockMvc + .perform(post("/owners/{ownerId}/pets/new", TEST_OWNER_ID).param("name", "Betty") + .param("birthDate", "2015-02-12")) + .andExpect(model().attributeHasNoErrors("owner")) + .andExpect(model().attributeHasErrors("pet")) + .andExpect(model().attributeHasFieldErrors("pet", "type")) + .andExpect(model().attributeHasFieldErrorCode("pet", "type", "required")) + .andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdatePetForm")); } @Test void testInitUpdateForm() throws Exception { mockMvc.perform(get("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID)) - .andExpect(status().isOk()).andExpect(model().attributeExists("pet")) - .andExpect(view().name("pets/createOrUpdatePetForm")); + .andExpect(status().isOk()) + .andExpect(model().attributeExists("pet")) + .andExpect(view().name("pets/createOrUpdatePetForm")); } @Test void testProcessUpdateFormSuccess() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") - .param("type", "hamster").param("birthDate", "2015-02-12")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); + mockMvc + .perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") + .param("type", "hamster") + .param("birthDate", "2015-02-12")) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); } @Test void testProcessUpdateFormHasErrors() throws Exception { - mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") - .param("birthDate", "2015/02/12")).andExpect(model().attributeHasNoErrors("owner")) - .andExpect(model().attributeHasErrors("pet")).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdatePetForm")); + mockMvc + .perform(post("/owners/{ownerId}/pets/{petId}/edit", TEST_OWNER_ID, TEST_PET_ID).param("name", "Betty") + .param("birthDate", "2015/02/12")) + .andExpect(model().attributeHasNoErrors("owner")) + .andExpect(model().attributeHasErrors("pet")) + .andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdatePetForm")); } } diff --git a/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java b/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java index 8a701d2..faeefda 100644 --- a/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/owner/VisitControllerTests.java @@ -69,22 +69,26 @@ void init() { @Test void testInitNewVisitForm() throws Exception { - mockMvc.perform(get("/owners/*/pets/{petId}/visits/new", TEST_PET_ID)).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdateVisitForm")); + mockMvc.perform(get("/owners/*/pets/{petId}/visits/new", TEST_PET_ID)) + .andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdateVisitForm")); } @Test void testProcessNewVisitFormSuccess() throws Exception { - mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID).param("name", "George") - .param("description", "Visit Description")).andExpect(status().is3xxRedirection()) - .andExpect(view().name("redirect:/owners/{ownerId}")); + mockMvc + .perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID).param("name", "George") + .param("description", "Visit Description")) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/owners/{ownerId}")); } @Test void testProcessNewVisitFormHasErrors() throws Exception { mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID).param("name", "George")) - .andExpect(model().attributeHasErrors("visit")).andExpect(status().isOk()) - .andExpect(view().name("pets/createOrUpdateVisitForm")); + .andExpect(model().attributeHasErrors("visit")) + .andExpect(status().isOk()) + .andExpect(view().name("pets/createOrUpdateVisitForm")); } } diff --git a/src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java b/src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java new file mode 100644 index 0000000..4edf2af --- /dev/null +++ b/src/test/java/org/springframework/samples/petclinic/system/CrashControllerIntegrationTests.java @@ -0,0 +1,98 @@ +/* + * Copyright 2012-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.samples.petclinic.system; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; + +/** + * Integration Test for {@link CrashController}. + * + * @author Alex Lutz + */ +// NOT Waiting https://github.com/spring-projects/spring-boot/issues/5574 +@SpringBootTest(webEnvironment = RANDOM_PORT, + properties = { "server.error.include-message=ALWAYS", "management.endpoints.enabled-by-default=false" }) +class CrashControllerIntegrationTests { + + @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) + static class TestConfiguration { + + } + + @Value(value = "${local.server.port}") + private int port; + + @Autowired + private TestRestTemplate rest; + + @Test + void testTriggerExceptionJson() { + ResponseEntity> resp = rest.exchange( + RequestEntity.get("http://localhost:" + port + "/oups").build(), + new ParameterizedTypeReference>() { + }); + assertThat(resp).isNotNull(); + assertThat(resp.getStatusCode().is5xxServerError()); + assertThat(resp.getBody().containsKey("timestamp")); + assertThat(resp.getBody().containsKey("status")); + assertThat(resp.getBody().containsKey("error")); + assertThat(resp.getBody()).containsEntry("message", + "Expected: controller used to showcase what happens when an exception is thrown"); + assertThat(resp.getBody()).containsEntry("path", "/oups"); + } + + @Test + void testTriggerExceptionHtml() { + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(List.of(MediaType.TEXT_HTML)); + ResponseEntity resp = rest.exchange("http://localhost:" + port + "/oups", HttpMethod.GET, + new HttpEntity<>(headers), String.class); + assertThat(resp).isNotNull(); + assertThat(resp.getStatusCode().is5xxServerError()); + assertThat(resp.getBody()).isNotNull(); + // html: + assertThat(resp.getBody()).containsSubsequence("", "

", "Something happened...", "

", "

", + "Expected:", "controller", "used", "to", "showcase", "what", "happens", "when", "an", "exception", "is", + "thrown", "

", ""); + // Not the whitelabel error page: + assertThat(resp.getBody()).doesNotContain("Whitelabel Error Page", + "This application has no explicit mapping for"); + } + +} diff --git a/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java b/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java index 06e7140..65d3b89 100644 --- a/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/system/CrashControllerTests.java @@ -16,33 +16,31 @@ package org.springframework.samples.petclinic.system; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.test.web.servlet.MockMvc; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import org.junit.jupiter.api.Test; /** * Test class for {@link CrashController} * * @author Colin But + * @author Alex Lutz */ -// Waiting https://github.com/spring-projects/spring-boot/issues/5574 -@Disabled -@WebMvcTest(controllers = CrashController.class) +// Waiting https://github.com/spring-projects/spring-boot/issues/5574 ..good +// luck ((plain(st) UNIT test)! :) class CrashControllerTests { - @Autowired - private MockMvc mockMvc; + CrashController testee = new CrashController(); @Test void testTriggerException() throws Exception { - mockMvc.perform(get("/oups")).andExpect(view().name("exception")) - .andExpect(model().attributeExists("exception")).andExpect(forwardedUrl("exception")) - .andExpect(status().isOk()); + RuntimeException thrown = assertThrows(RuntimeException.class, () -> { + testee.triggerException(); + }); + + assertEquals("Expected: controller used to showcase what happens when an exception is thrown", + thrown.getMessage()); } } diff --git a/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java b/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java index 3bf82e4..2ac92b7 100644 --- a/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java +++ b/src/test/java/org/springframework/samples/petclinic/vet/VetControllerTests.java @@ -80,17 +80,19 @@ void setup() { @Test void testShowVetListHtml() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/vets.html?page=1")).andExpect(status().isOk()) - .andExpect(model().attributeExists("vets")).andExpect(view().name("vets/vetList")); + mockMvc.perform(MockMvcRequestBuilders.get("/vets.html?page=1")) + .andExpect(status().isOk()) + .andExpect(model().attributeExists("vets")) + .andExpect(view().name("vets/vetList")); } @Test void testShowResourcesVetList() throws Exception { ResultActions actions = mockMvc.perform(get("/vets").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); + .andExpect(status().isOk()); actions.andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.vetList[0].id").value(1)); + .andExpect(jsonPath("$.vetList[0].id").value(1)); } }