Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
1 result

Target

Select target project
  • s51119/broken-petclinic
  • s72462/broken-petclinic
  • s61200/broken-petclinic
  • s76620/broken-petclinic
  • s76545/broken-petclinic
  • s76915/broken-petclinic
  • s70130/broken-petclinic
  • s72523/broken-petclinic
  • s77047/broken-petclinic
  • s70178/broken-petclinic
  • s76522/broken-petclinic
  • s76426/broken-petclinic
  • s76863/broken-petclinic
  • s76856/broken-petclinic
  • s76728/broken-petclinic
  • williamreetz/broken-petclinic
  • s77034/broken-petclinic
  • s76400/broken-petclinic
  • s72288/broken-petclinic
  • s76608/broken-petclinic
20 results
Select Git revision
  • master
1 result
Show changes
Showing
with 613 additions and 435 deletions
All Spring config files (including Spring MVC ones) are inside src/main/resource.
There are mostly 2 reasons to that:
- All Spring config files are grouped into one single place
- It is simpler to reference them from inside JUnit tests
\ No newline at end of file
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ attribute name="name" required="true" rtexprvalue="true"
description="Name of corresponding property in bean object" %>
<%@ attribute name="label" required="true" rtexprvalue="true"
description="Label appears in red color if input is considered as invalid after submission" %>
<spring:bind path="${name}">
<c:set var="cssGroup" value="control-group ${status.error ? 'error' : '' }"/>
<div class="${cssGroup}">
<label class="control-label">${label}</label>
<div class="controls">
<form:input path="${name}"/>
<span class="help-inline">${status.errorMessage}</span>
</div>
</div>
</spring:bind>
\ No newline at end of file
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ attribute name="name" required="true" rtexprvalue="true"
description="Name of corresponding property in bean object" %>
<%@ attribute name="label" required="true" rtexprvalue="true"
description="Label appears in red color if input is considered as invalid after submission" %>
<%@ attribute name="names" required="true" rtexprvalue="true" type="java.util.List"
description="Names in the list" %>
<%@ attribute name="size" required="true" rtexprvalue="true"
description="Size of Select" %>
<spring:bind path="${name}">
<c:set var="cssGroup" value="control-group ${status.error ? 'error' : '' }"/>
<div class="${cssGroup}">
<label class="control-label">${label}</label>
<div class="controls">
<form:select path="${name}" items="${names}" size="${size}"/>
<span class="help-inline">${status.errorMessage}</span>
</div>
</div>
</spring:bind>
\ No newline at end of file
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring PetClinic</display-name>
<description>Spring PetClinic sample application</description>
<!-- Default profile is "jpa" (see business-config.xml for more details).
When using Spring JDBC, uncomment the following: -->
<!-- <context-param>
<param-name>spring.profiles.active</param-name>
<param-value>jdbc</param-value>
</context-param> -->
<!-- When using Spring Data JPA, uncomment the following: -->
<!--
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>spring-data-jpa</param-value>
</context-param>
-->
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/business-config.xml, classpath:spring/tools-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>petclinic</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/mvc-core-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>petclinic</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Dandelion-Datatables servlet definition -->
<servlet>
<servlet-name>datatablesController</servlet-name>
<servlet-class>com.github.dandelion.datatables.extras.servlet2.servlet.DatatablesServlet</servlet-class>
</servlet>
<!-- Dandelion-Datatables servlet mapping -->
<servlet-mapping>
<servlet-name>datatablesController</servlet-name>
<url-pattern>/datatablesController/*</url-pattern>
</servlet-mapping>
<!-- used so we can use forms of method type 'PUT' and 'DELETE' (such as in the Pet form)
see here: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/view.html#rest-method-conversion
-->
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<servlet-name>petclinic</servlet-name>
</filter-mapping>
<!-- used to provide the ability to enter Chinese characters inside the Owner Form -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Dandelion-Datatables filter definition -->
<filter>
<filter-name>datatablesFilter</filter-name>
<filter-class>com.github.dandelion.datatables.extras.servlet2.filter.DatatablesFilter</filter-class>
</filter>
<!-- Dandelion-Datatables filter mapping -->
<filter-mapping>
<filter-name>datatablesFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
\ No newline at end of file
.container {
padding-top: 10px;
margin-left: 50px;
width: 700px;
}
.form-horizontal {
width: 100%;
}
input[type="text"] {
height: 25px;
}
.navbar .nav > li > a {
color: #000000;
}
.form-horizontal .control-label {
text-align: left;
}
src/main/webapp/resources/images/banner-graphic.png

13.5 KiB

src/main/webapp/resources/images/bullet-arrow.png

2.88 KiB

src/main/webapp/resources/images/pets.png

54 KiB

src/main/webapp/resources/images/springsource-logo.png

4.86 KiB

src/main/webapp/resources/images/submit-bg.png

2.75 KiB

#List of preProcessors
preProcessors=lessCssImport
#List of postProcessors
postProcessors=less4j
\ No newline at end of file
<groups xmlns="http://www.isdc.ro/wro">
<group name="petclinic">
<css>classpath:META-INF/resources/webjars/bootstrap/3.3.6/less/bootstrap.less</css>
<css>/petclinic.less</css>
</group>
</groups>
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
...@@ -13,32 +13,27 @@ ...@@ -13,32 +13,27 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.samples.petclinic.model;
import static org.junit.Assert.assertEquals; package org.springframework.samples.petclinic;
import static org.junit.Assert.assertNull;
import org.junit.Test; import org.junit.Test;
import org.springframework.transaction.annotation.Transactional; import org.junit.runner.RunWith;
/** import org.springframework.beans.factory.annotation.Autowired;
* JUnit test for the {@link Owner} class. import org.springframework.boot.test.context.SpringBootTest;
* import org.springframework.samples.petclinic.vet.VetRepository;
* @author Ken Krebs import org.springframework.test.context.junit4.SpringRunner;
*/
public class OwnerTests { @RunWith(SpringRunner.class)
@SpringBootTest
public class PetclinicIntegrationTests {
@Autowired
private VetRepository vets;
@Test @Test
@Transactional public void testFindAll() throws Exception {
public void testHasPet() { vets.findAll();
Owner owner = new Owner(); vets.findAll(); // served from cache
Pet fido = new Pet();
fido.setName("Fido");
assertNull(owner.getPet("Fido"));
assertNull(owner.getPet("fido"));
owner.addPet(fido);
assertEquals(fido, owner.getPet("Fido"));
assertEquals(fido, owner.getPet("fido"));
} }
} }
/*
* 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.model; package org.springframework.samples.petclinic.model;
import java.util.Locale;
import java.util.Set; import java.util.Set;
import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolation;
import javax.validation.Validator; import javax.validation.Validator;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* * @author Michael Isvy Simple test to make sure that Bean Validation is working (useful
* @author Michael Isvy * when upgrading to a new version of Hibernate Validator/ Bean Validation)
* Simple test to make sure that Bean Validation is working
* (useful when upgrading to a new version of Hibernate Validator/ Bean Validation)
*
*/ */
public class ValidatorTests { public class ValidatorTests {
private Validator createValidator() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.afterPropertiesSet();
return localValidatorFactoryBean;
}
@Test private Validator createValidator() {
public void emptyFirstName() { LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.afterPropertiesSet();
return localValidatorFactoryBean;
}
@Test
public void shouldNotValidateWhenFirstNameEmpty() {
LocaleContextHolder.setLocale(Locale.ENGLISH);
Person person = new Person(); Person person = new Person();
person.setFirstName(""); person.setFirstName("");
person.setLastName("smith"); person.setLastName("smith");
Validator validator = createValidator(); Validator validator = createValidator();
Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person); Set<ConstraintViolation<Person>> constraintViolations = validator
.validate(person);
Assert.assertEquals(1, constraintViolations.size()); assertThat(constraintViolations.size()).isEqualTo(1);
ConstraintViolation<Person> violation = constraintViolations.iterator().next(); ConstraintViolation<Person> violation = constraintViolations.iterator().next();
Assert.assertEquals(violation.getPropertyPath().toString(), "firstName"); assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
Assert.assertEquals(violation.getMessage(), "may not be empty"); assertThat(violation.getMessage()).isEqualTo("must not be empty");
} }
} }
/*
* 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.owner;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.samples.petclinic.owner.Owner;
import org.springframework.samples.petclinic.owner.OwnerController;
import org.springframework.samples.petclinic.owner.OwnerRepository;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
/**
* Test class for {@link OwnerController}
*
* @author Colin But
*/
@RunWith(SpringRunner.class)
@WebMvcTest(OwnerController.class)
public class OwnerControllerTests {
private static final int TEST_OWNER_ID = 1;
@Autowired
private MockMvc mockMvc;
@MockBean
private OwnerRepository owners;
private Owner george;
@Before
public void setup() {
george = new Owner();
george.setId(TEST_OWNER_ID);
george.setFirstName("George");
george.setLastName("Franklin");
george.setAddress("110 W. Liberty St.");
george.setCity("Madison");
george.setTelephone("6085551023");
given(this.owners.findById(TEST_OWNER_ID)).willReturn(george);
}
@Test
public void testInitCreationForm() throws Exception {
mockMvc.perform(get("/owners/new"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("owner"))
.andExpect(view().name("owners/createOrUpdateOwnerForm"));
}
@Test
public 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());
}
@Test
public 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"));
}
@Test
public void testInitFindForm() throws Exception {
mockMvc.perform(get("/owners/find"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("owner"))
.andExpect(view().name("owners/findOwners"));
}
@Test
public void testProcessFindFormSuccess() throws Exception {
given(this.owners.findByLastName("")).willReturn(Lists.newArrayList(george, new Owner()));
mockMvc.perform(get("/owners"))
.andExpect(status().isOk())
.andExpect(view().name("owners/ownersList"));
}
@Test
public void testProcessFindFormByLastName() throws Exception {
given(this.owners.findByLastName(george.getLastName())).willReturn(Lists.newArrayList(george));
mockMvc.perform(get("/owners")
.param("lastName", "Franklin")
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/" + TEST_OWNER_ID));
}
@Test
public void testProcessFindFormNoOwnersFound() throws Exception {
mockMvc.perform(get("/owners")
.param("lastName", "Unknown Surname")
)
.andExpect(status().isOk())
.andExpect(model().attributeHasFieldErrors("owner", "lastName"))
.andExpect(model().attributeHasFieldErrorCode("owner", "lastName", "notFound"))
.andExpect(view().name("owners/findOwners"));
}
@Test
public 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"));
}
@Test
public 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}"));
}
@Test
public 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"));
}
@Test
public 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(view().name("owners/ownerDetails"));
}
}
/*
* 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.owner;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.samples.petclinic.owner.Owner;
import org.springframework.samples.petclinic.owner.OwnerRepository;
import org.springframework.samples.petclinic.owner.Pet;
import org.springframework.samples.petclinic.owner.PetController;
import org.springframework.samples.petclinic.owner.PetRepository;
import org.springframework.samples.petclinic.owner.PetType;
import org.springframework.samples.petclinic.owner.PetTypeFormatter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
/**
* Test class for the {@link PetController}
*
* @author Colin But
*/
@RunWith(SpringRunner.class)
@WebMvcTest(value = PetController.class,
includeFilters = @ComponentScan.Filter(
value = PetTypeFormatter.class,
type = FilterType.ASSIGNABLE_TYPE))
public class PetControllerTests {
private static final int TEST_OWNER_ID = 1;
private static final int TEST_PET_ID = 1;
@Autowired
private MockMvc mockMvc;
@MockBean
private PetRepository pets;
@MockBean
private OwnerRepository owners;
@Before
public void setup() {
PetType cat = new PetType();
cat.setId(3);
cat.setName("hamster");
given(this.pets.findPetTypes()).willReturn(Lists.newArrayList(cat));
given(this.owners.findById(TEST_OWNER_ID)).willReturn(new Owner());
given(this.pets.findById(TEST_PET_ID)).willReturn(new Pet());
}
@Test
public 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"));
}
@Test
public 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}"));
}
@Test
public 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"));
}
@Test
public 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"));
}
@Test
public 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}"));
}
@Test
public 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"));
}
}
/*
* 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.owner;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
/**
* Test class for {@link PetTypeFormatter}
*
* @author Colin But
*/
@RunWith(MockitoJUnitRunner.class)
public class PetTypeFormatterTests {
@Mock
private PetRepository pets;
private PetTypeFormatter petTypeFormatter;
@Before
public void setup() {
this.petTypeFormatter = new PetTypeFormatter(pets);
}
@Test
public void testPrint() {
PetType petType = new PetType();
petType.setName("Hamster");
String petTypeName = this.petTypeFormatter.print(petType, Locale.ENGLISH);
assertEquals("Hamster", petTypeName);
}
@Test
public void shouldParse() throws ParseException {
Mockito.when(this.pets.findPetTypes()).thenReturn(makePetTypes());
PetType petType = petTypeFormatter.parse("Bird", Locale.ENGLISH);
assertEquals("Bird", petType.getName());
}
@Test(expected = ParseException.class)
public void shouldThrowParseException() throws ParseException {
Mockito.when(this.pets.findPetTypes()).thenReturn(makePetTypes());
petTypeFormatter.parse("Fish", Locale.ENGLISH);
}
/**
* Helper method to produce some sample pet types just for test purpose
*
* @return {@link Collection} of {@link PetType}
*/
private List<PetType> makePetTypes() {
List<PetType> petTypes = new ArrayList<>();
petTypes.add(new PetType() {
{
setName("Dog");
}
});
petTypes.add(new PetType() {
{
setName("Bird");
}
});
return petTypes;
}
}
/*
* 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.owner;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.samples.petclinic.owner.Pet;
import org.springframework.samples.petclinic.owner.PetRepository;
import org.springframework.samples.petclinic.owner.VisitController;
import org.springframework.samples.petclinic.visit.VisitRepository;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
/**
* Test class for {@link VisitController}
*
* @author Colin But
*/
@RunWith(SpringRunner.class)
@WebMvcTest(VisitController.class)
public class VisitControllerTests {
private static final int TEST_PET_ID = 1;
@Autowired
private MockMvc mockMvc;
@MockBean
private VisitRepository visits;
@MockBean
private PetRepository pets;
@Before
public void init() {
given(this.pets.findById(TEST_PET_ID)).willReturn(new Pet());
}
@Test
public void testInitNewVisitForm() throws Exception {
mockMvc.perform(get("/owners/*/pets/{petId}/visits/new", TEST_PET_ID))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdateVisitForm"));
}
@Test
public 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}"));
}
@Test
public 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"));
throw new Exception();
}
}
/*
* Copyright 2002-2013 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
*
* http://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.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.model.Vet;
import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.util.EntityUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* <p> Base class for {@link ClinicService} integration tests. </p> <p> Subclasses should specify Spring context
* configuration using {@link ContextConfiguration @ContextConfiguration} annotation </p> <p>
* AbstractclinicServiceTests and its subclasses benefit from the following services provided by the Spring
* TestContext Framework: </p> <ul> <li><strong>Spring IoC container caching</strong> which spares us unnecessary set up
* time between test execution.</li> <li><strong>Dependency Injection</strong> of test fixture instances, meaning that
* we don't need to perform application context lookups. See the use of {@link Autowired @Autowired} on the <code>{@link
* AbstractclinicServiceTests#clinicService clinicService}</code> instance variable, which uses autowiring <em>by
* type</em>. <li><strong>Transaction management</strong>, meaning each test method is executed in its own transaction,
* which is automatically rolled back by default. Thus, even if tests insert or otherwise change database state, there
* is no need for a teardown or cleanup script. <li> An {@link org.springframework.context.ApplicationContext
* ApplicationContext} is also inherited and can be used for explicit bean lookup if necessary. </li> </ul>
*
* @author Ken Krebs
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
* @author Michael Isvy
*/
public abstract class AbstractClinicServiceTests {
@Autowired
protected ClinicService clinicService;
@Test
@Transactional
public void findOwners() {
Collection<Owner> owners = this.clinicService.findOwnerByLastName("Davis");
assertEquals(2, owners.size());
owners = this.clinicService.findOwnerByLastName("Daviss");
assertEquals(0, owners.size());
}
@Test
public void findSingleOwner() {
Owner owner1 = this.clinicService.findOwnerById(1);
assertTrue(owner1.getLastName().startsWith("Franklin"));
Owner owner10 = this.clinicService.findOwnerById(10);
assertEquals("Carlos", owner10.getFirstName());
assertEquals(owner1.getPets().size(), 1);
}
@Test
@Transactional
public void insertOwner() {
Collection<Owner> owners = this.clinicService.findOwnerByLastName("Schultz");
int found = owners.size();
Owner owner = new Owner();
owner.setFirstName("Sam");
owner.setLastName("Schultz");
owner.setAddress("4, Evans Street");
owner.setCity("Wollongong");
owner.setTelephone("4444444444");
this.clinicService.saveOwner(owner);
Assert.assertNotEquals("Owner Id should have been generated", owner.getId().longValue(), 0);
owners = this.clinicService.findOwnerByLastName("Schultz");
assertEquals("Verifying number of owners after inserting a new one.", found + 1, owners.size());
}
@Test
@Transactional
public void updateOwner() throws Exception {
Owner o1 = this.clinicService.findOwnerById(1);
String old = o1.getLastName();
o1.setLastName(old + "X");
this.clinicService.saveOwner(o1);
o1 = this.clinicService.findOwnerById(1);
assertEquals(old + "X", o1.getLastName());
}
@Test
public void findPet() {
Collection<PetType> types = this.clinicService.findPetTypes();
Pet pet7 = this.clinicService.findPetById(7);
assertTrue(pet7.getName().startsWith("Samantha"));
assertEquals(EntityUtils.getById(types, PetType.class, 1).getId(), pet7.getType().getId());
assertEquals("Jean", pet7.getOwner().getFirstName());
Pet pet6 = this.clinicService.findPetById(6);
assertEquals("George", pet6.getName());
assertEquals(EntityUtils.getById(types, PetType.class, 4).getId(), pet6.getType().getId());
assertEquals("Peter", pet6.getOwner().getFirstName());
}
@Test
public void getPetTypes() {
Collection<PetType> petTypes = this.clinicService.findPetTypes();
PetType petType1 = EntityUtils.getById(petTypes, PetType.class, 1);
assertEquals("cat", petType1.getName());
PetType petType4 = EntityUtils.getById(petTypes, PetType.class, 4);
assertEquals("snake", petType4.getName());
}
@Test
@Transactional
public void insertPet() {
Owner owner6 = this.clinicService.findOwnerById(6);
int found = owner6.getPets().size();
Pet pet = new Pet();
pet.setName("bowser");
Collection<PetType> types = this.clinicService.findPetTypes();
pet.setType(EntityUtils.getById(types, PetType.class, 2));
pet.setBirthDate(new DateTime());
owner6.addPet(pet);
assertEquals(found + 1, owner6.getPets().size());
// both storePet and storeOwner are necessary to cover all ORM tools
this.clinicService.savePet(pet);
this.clinicService.saveOwner(owner6);
owner6 = this.clinicService.findOwnerById(6);
assertEquals(found + 1, owner6.getPets().size());
assertNotNull("Pet Id should have been generated", pet.getId());
}
@Test
@Transactional
public void updatePet() throws Exception {
Pet pet7 = this.clinicService.findPetById(7);
String old = pet7.getName();
pet7.setName(old + "X");
this.clinicService.savePet(pet7);
pet7 = this.clinicService.findPetById(7);
assertEquals(old + "X", pet7.getName());
}
@Test
public void findVets() {
Collection<Vet> vets = this.clinicService.findVets();
Vet v1 = EntityUtils.getById(vets, Vet.class, 2);
assertEquals("Leary", v1.getLastName());
assertEquals(1, v1.getNrOfSpecialties());
assertEquals("radiology", (v1.getSpecialties().get(0)).getName());
Vet v2 = EntityUtils.getById(vets, Vet.class, 3);
assertEquals("Douglas", v2.getLastName());
assertEquals(2, v2.getNrOfSpecialties());
assertEquals("dentistry", (v2.getSpecialties().get(0)).getName());
assertEquals("surgery", (v2.getSpecialties().get(1)).getName());
}
@Test
@Transactional
public void insertVisit() {
Pet pet7 = this.clinicService.findPetById(7);
int found = pet7.getVisits().size();
Visit visit = new Visit();
pet7.addVisit(visit);
visit.setDescription("test");
// both storeVisit and storePet are necessary to cover all ORM tools
this.clinicService.saveVisit(visit);
this.clinicService.savePet(pet7);
pet7 = this.clinicService.findPetById(7);
assertEquals(found + 1, pet7.getVisits().size());
assertNotNull("Visit Id should have been generated", visit.getId());
}
}
/*
* Copyright 2002-2013 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
*
* http://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.service;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p> Integration test using the jdbc profile.
* @see AbstractClinicServiceTests AbstractClinicServiceTests for more details. </p>
*
* @author Thomas Risberg
* @author Michael Isvy
*/
@ContextConfiguration(locations = {"classpath:spring/business-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jdbc")
public class ClinicServiceJdbcTests extends AbstractClinicServiceTests {
}