From d5f65ea2abd54bd1d9d8fda79f20c2bfdb7b3223 Mon Sep 17 00:00:00 2001 From: PunCha Date: Wed, 17 Aug 2016 23:24:00 +0800 Subject: [PATCH 01/29] Add more unit tests for domain models --- src/main/java/tk/puncha/models/Visit.java | 2 +- src/test/java/tk/puncha/TestUtil.java | 39 ++++++++++ .../tk/puncha/unit/models/OwnerTests.java | 76 ++++--------------- .../java/tk/puncha/unit/models/PetTests.java | 60 +++++++++++++++ .../tk/puncha/unit/models/PetTypeTests.java | 25 ++++++ src/test/java/tk/puncha/unit/models/README.md | 4 + .../tk/puncha/unit/models/VisitTests.java | 35 +++++++++ 7 files changed, 177 insertions(+), 64 deletions(-) create mode 100644 src/test/java/tk/puncha/TestUtil.java create mode 100644 src/test/java/tk/puncha/unit/models/PetTests.java create mode 100644 src/test/java/tk/puncha/unit/models/PetTypeTests.java create mode 100644 src/test/java/tk/puncha/unit/models/README.md create mode 100644 src/test/java/tk/puncha/unit/models/VisitTests.java diff --git a/src/main/java/tk/puncha/models/Visit.java b/src/main/java/tk/puncha/models/Visit.java index 7910ffc..ebcc337 100644 --- a/src/main/java/tk/puncha/models/Visit.java +++ b/src/main/java/tk/puncha/models/Visit.java @@ -13,7 +13,7 @@ public class Visit { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; + private int id = -1; private String description; @Column(name = "VISIT_DATE") diff --git a/src/test/java/tk/puncha/TestUtil.java b/src/test/java/tk/puncha/TestUtil.java new file mode 100644 index 0000000..d01c992 --- /dev/null +++ b/src/test/java/tk/puncha/TestUtil.java @@ -0,0 +1,39 @@ +package tk.puncha; + +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; + +import javax.validation.ConstraintViolation; +import javax.validation.Validator; +import java.util.Locale; +import java.util.Set; + +import static org.junit.Assert.assertEquals; + +public abstract class TestUtil { + + public static Validator createValidator() { + LocaleContextHolder.setLocale(Locale.ENGLISH); + ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setFallbackToSystemLocale(false); + messageSource.setBasenames("validation"); + messageSource.setDefaultEncoding("utf8"); + + LocalValidatorFactoryBean localValidator = new LocalValidatorFactoryBean(); + localValidator.setValidationMessageSource(messageSource); + localValidator.afterPropertiesSet(); + return localValidator; + } + + + public static void assertViolation( + T objToValidate, String property, Object invalidValue, String message) { + Set> violations = createValidator().validate(objToValidate); + assertEquals(1, violations.size()); + ConstraintViolation violation = violations.iterator().next(); + assertEquals(property, violation.getPropertyPath().toString()); + assertEquals(invalidValue, violation.getInvalidValue()); + assertEquals(message, violation.getMessage()); + } +} diff --git a/src/test/java/tk/puncha/unit/models/OwnerTests.java b/src/test/java/tk/puncha/unit/models/OwnerTests.java index 45a3138..0ec5fd5 100644 --- a/src/test/java/tk/puncha/unit/models/OwnerTests.java +++ b/src/test/java/tk/puncha/unit/models/OwnerTests.java @@ -1,58 +1,29 @@ package tk.puncha.unit.models; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import tk.puncha.TestUtil; import tk.puncha.models.Owner; import javax.validation.ConstraintViolation; -import javax.validation.Validator; -import java.util.Locale; import java.util.Set; import static org.junit.Assert.*; public class OwnerTests { - private static Validator validator; private Owner owner; - @BeforeClass - static public void beforeClass() { - LocaleContextHolder.setLocale(Locale.ENGLISH); - ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setFallbackToSystemLocale(false); - messageSource.setBasenames("validation"); - messageSource.setDefaultEncoding("utf8"); - - LocalValidatorFactoryBean localValidator = new LocalValidatorFactoryBean(); - localValidator.setValidationMessageSource(messageSource); - localValidator.afterPropertiesSet(); - validator = localValidator; - } - @Before public void before() { this.owner = new Owner(); } - private void makeOwnerValid() { + private void makeValid() { owner.setFirstName("firstname"); owner.setLastName("lastname"); } - private void assertNameInvalid(String propertyName, String name, String message) { - Set> violations = validator.validate(owner); - assertEquals(1, violations.size()); - ConstraintViolation violation = violations.iterator().next(); - assertEquals(propertyName, violation.getPropertyPath().toString()); - assertEquals(name, violation.getInvalidValue()); - assertEquals(message, violation.getMessage()); - } - @Test public void shouldDefaultOwnerWellInitialized() throws Exception { assertEquals(-1, owner.getId()); @@ -64,61 +35,40 @@ public void shouldDefaultOwnerWellInitialized() throws Exception { assertNotNull(owner.getPets()); } - @Test - public void shouldPropertiesFunctional() throws Exception { - owner.setId(100); - assertEquals(100, owner.getId()); - - owner.setFirstName("first name"); - assertEquals("first name", owner.getFirstName()); - - owner.setLastName("last name"); - assertEquals("last name", owner.getLastName()); - - owner.setCity("city"); - assertEquals("city", owner.getCity()); - - owner.setAddress("address"); - assertEquals("address", owner.getAddress()); - - owner.setTelephone("tele"); - assertEquals("tele", owner.getTelephone()); - } - @Test public void shouldDefaultOwnerNotValidate() throws Exception { - Set> violations = validator.validate(owner); + Set> violations = TestUtil.createValidator().validate(owner); assertEquals(2, violations.size()); } @Test public void shouldNotValidateIfLengthOfFirstNameLessThan3() throws Exception { - makeOwnerValid(); + makeValid(); owner.setFirstName("12"); - assertNameInvalid("firstName", "12", "Size of First name must be between 3 and 30"); + TestUtil.assertViolation(owner, "firstName", "12", "Size of First name must be between 3 and 30"); } @Test public void shouldNotValidateIfLengthOfLastNameLessThan3() throws Exception { - makeOwnerValid(); + makeValid(); owner.setLastName("12"); - assertNameInvalid("lastName", "12", "Size of Last name must be between 3 and 30"); + TestUtil.assertViolation(owner, "lastName", "12", "Size of Last name must be between 3 and 30"); } @Test public void shouldNotValidateIfLengthOfFirstNameLargeThan30() throws Exception { - makeOwnerValid(); - String name = String.format("%1$31s", "A"); + makeValid(); + final String name = String.format("%1$31s", "A"); owner.setFirstName(name); // 31 A - assertNameInvalid("firstName", name, "Size of First name must be between 3 and 30"); + TestUtil.assertViolation(owner, "firstName", name, "Size of First name must be between 3 and 30"); } @Test public void shouldNotValidateIfLengthOfLastNameLargeThan30() throws Exception { - makeOwnerValid(); - String name = String.format("%1$31s", "A"); + makeValid(); + final String name = String.format("%1$31s", "A"); owner.setLastName(name); // 31 A - assertNameInvalid("lastName", name, "Size of Last name must be between 3 and 30"); + TestUtil.assertViolation(owner, "lastName", name, "Size of Last name must be between 3 and 30"); } } diff --git a/src/test/java/tk/puncha/unit/models/PetTests.java b/src/test/java/tk/puncha/unit/models/PetTests.java new file mode 100644 index 0000000..9faecaf --- /dev/null +++ b/src/test/java/tk/puncha/unit/models/PetTests.java @@ -0,0 +1,60 @@ +package tk.puncha.unit.models; + +import org.junit.Before; +import org.junit.Test; +import tk.puncha.TestUtil; +import tk.puncha.models.Owner; +import tk.puncha.models.Pet; +import tk.puncha.models.PetType; + +import javax.validation.ConstraintViolation; +import java.util.Set; + +import static org.junit.Assert.*; + +public class PetTests { + + private Pet pet; + + @Before + public void before() { + this.pet = new Pet(); + } + + private void makeValid() { + pet.setName("petName"); + pet.setOwner(new Owner()); + pet.setType(new PetType()); + } + + @Test + public void shouldDefaultPetWellInitialized() throws Exception { + assertEquals(-1, pet.getId()); + assertNull(pet.getName()); + assertNull(pet.getType()); + assertNull(pet.getBirthDate()); + assertNotNull(pet.getVisits()); + assertTrue(pet.getVisits().isEmpty()); + } + + @Test + public void shouldDefaultPetNotValidate() throws Exception { + Set> violations = TestUtil.createValidator().validate(pet); + assertEquals(2, violations.size()); // owner, type + } + + @Test + public void shouldNotValidateIfLengthOfNameLessThan3() throws Exception { + makeValid(); + pet.setName("12"); + TestUtil.assertViolation(pet, "name", "12", "Size of name must be between 3 and 30"); + } + + @Test + public void shouldNotValidateIfLengthOfNameLargeThan30() throws Exception { + makeValid(); + String name = String.format("%1$31s", "A"); + pet.setName(name); // 31 A + TestUtil.assertViolation(pet, "name", name, "Size of name must be between 3 and 30"); + } +} diff --git a/src/test/java/tk/puncha/unit/models/PetTypeTests.java b/src/test/java/tk/puncha/unit/models/PetTypeTests.java new file mode 100644 index 0000000..3387608 --- /dev/null +++ b/src/test/java/tk/puncha/unit/models/PetTypeTests.java @@ -0,0 +1,25 @@ +package tk.puncha.unit.models; + +import org.junit.Before; +import org.junit.Test; +import tk.puncha.models.PetType; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class PetTypeTests { + + private PetType petType; + + @Before + public void before() { + this.petType = new PetType(); + } + + @Test + public void shouldDefaultVisitWellInitialized() throws Exception { + assertEquals(-1, petType.getId()); + assertNull(petType.getName()); + } + +} diff --git a/src/test/java/tk/puncha/unit/models/README.md b/src/test/java/tk/puncha/unit/models/README.md new file mode 100644 index 0000000..3d8c88d --- /dev/null +++ b/src/test/java/tk/puncha/unit/models/README.md @@ -0,0 +1,4 @@ +These are tests for Models. They mainly verify: +- properties are well initialized. +- constrains on properties take effects. + diff --git a/src/test/java/tk/puncha/unit/models/VisitTests.java b/src/test/java/tk/puncha/unit/models/VisitTests.java new file mode 100644 index 0000000..3156e4f --- /dev/null +++ b/src/test/java/tk/puncha/unit/models/VisitTests.java @@ -0,0 +1,35 @@ +package tk.puncha.unit.models; + +import org.junit.Before; +import org.junit.Test; +import tk.puncha.TestUtil; +import tk.puncha.models.Visit; + +import javax.validation.ConstraintViolation; +import java.util.Set; + +import static org.junit.Assert.*; + +public class VisitTests { + + private Visit visit; + + @Before + public void before() { + this.visit = new Visit(); + } + + @Test + public void shouldDefaultVisitWellInitialized() throws Exception { + assertEquals(-1, visit.getId()); + assertNull(visit.getDescription()); + assertNull(visit.getPet()); + assertNull(visit.getVisitDate()); + } + + @Test + public void shouldDefaultVisitNotValidate() throws Exception { + Set> violations = TestUtil.createValidator().validate(visit); + assertEquals(1, violations.size()); // visitDate + } +} From 98d45088931326869b0d3e3de9774040d93d7c4d Mon Sep 17 00:00:00 2001 From: PunCha Date: Thu, 18 Aug 2016 02:53:11 +0800 Subject: [PATCH 02/29] Add integration test for HibernateOwnerDAO --- .../dao/hibernate/HibernateOwnerDAO.java | 3 +- .../puncha/integration/daos/OwnerDAOTest.java | 147 ++++++++++++++++++ 2 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java diff --git a/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java b/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java index 9b9a099..25351ed 100644 --- a/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java +++ b/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java @@ -7,6 +7,7 @@ import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; import tk.puncha.controllers.PetController; import tk.puncha.dao.OwnerDAO; import tk.puncha.models.Owner; @@ -52,7 +53,7 @@ public Owner getOwnerWithPetsById(int ownerId) { String query = "select owner from Owner owner left join fetch owner.pets where owner.id = :ownerId"; return em.createQuery(query, Owner.class) .setParameter("ownerId", ownerId) - .getSingleResult(); + .getResultList().stream().findFirst().orElse(null); } @Override diff --git a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java new file mode 100644 index 0000000..737c1e5 --- /dev/null +++ b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java @@ -0,0 +1,147 @@ +package tk.puncha.integration.daos; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; +import tk.puncha.dao.OwnerDAO; +import tk.puncha.models.Owner; + +import javax.persistence.EntityNotFoundException; +import javax.persistence.Persistence; +import javax.persistence.PersistenceException; +import javax.validation.ConstraintViolationException; +import java.util.List; + +import static junit.framework.TestCase.assertFalse; +import static org.junit.Assert.*; + +@ActiveProfiles("hibernate,mysql") +@TestPropertySource(locations = {"/test.properties"}) +@AutoConfigureTestDatabase +@Transactional +@Rollback +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +@RunWith(SpringJUnit4ClassRunner.class) +public class OwnerDAOTest { + @Autowired + private OwnerDAO ownerDAO; + + @Test + public void shouldGetAllOwnersReturnAllOwnersList() throws Exception { + List owners = ownerDAO.getAllOwners(); + assertEquals(10, owners.size()); + } + + @Test + public void shouldGetOwnerByIdReturnOwnerWhenOwnerExists() throws Exception { + Owner owner = ownerDAO.getOwnerById(1); + assertNotNull(owner); + assertEquals(1, owner.getId()); + assertFalse(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); + } + + @Test + public void shouldGetOwnerByIdReturnNullWhenOwnerNotExists() throws Exception { + Owner owner = ownerDAO.getOwnerById(-1); + assertNull(owner); + } + + @Test + public void shouldGetOwnerWithPetsByIdReturnOwnerWithPetsWhenOwnerExists() throws Exception { + Owner owner = ownerDAO.getOwnerWithPetsById(1); + assertNotNull(owner); + assertEquals(1, owner.getId()); + assertTrue(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); + } + + @Test + public void shouldGetOwnerWithPetsByIdReturnNullWhenOwnerNotExists() throws Exception { + Owner owner = ownerDAO.getOwnerWithPetsById(-1); + assertNull(owner); + } + + @Test + public void shouldGetOwnersByFirstNameReturnMatchedOwnersList() throws Exception { + List owners = ownerDAO.getOwnersByFirstName("eT"); + assertEquals(2, owners.size()); + } + + @Test + public void shouldGetOwnersByFirstNameReturnEmptyListWhenOnMatchedOwners() throws Exception { + List owners = ownerDAO.getOwnersByFirstName("puncha"); + assertTrue(owners.isEmpty()); + } + + @Test + public void shouldInsertOwnerSuccessWhenOwnerIsValid() throws Exception { + Owner owner = new Owner(); + owner.setFirstName("puncha"); + owner.setLastName("feng"); + owner.setAddress("sample address"); + int id = ownerDAO.insertOwner(owner); + assertNotEquals(-1, id); + } + + @Test(expected = ConstraintViolationException.class) + public void shouldInsertOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception { + Owner owner = new Owner(); + ownerDAO.insertOwner(owner); + } + + @Test(expected = PersistenceException.class) + public void shouldInsertOwnerThrowExceptionWhenOwnerIdIsNotDefault() throws Exception { + Owner owner = new Owner(); + owner.setId(123); + ownerDAO.insertOwner(owner); + } + + @Test + public void shouldUpdateOwnerSucceededWhenOwnerIsValid() { + Owner owner = ownerDAO.getOwnerById(1); + owner.setFirstName("puncha"); + ownerDAO.updateOwner(owner); + List matchedOwners = ownerDAO.getOwnersByFirstName("puncha"); + assertEquals(1, matchedOwners.size()); + } + + + @Test(expected = ConstraintViolationException.class) + public void shouldUpdateOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception { + Owner owner = ownerDAO.getOwnerById(1); + owner.setFirstName("AB"); + ownerDAO.updateOwner(owner); + // HACK: the query actually force Hibernate to execute the UPDATE SQL statement, + // or the @Rollback suppresses the Update SQL statement to fail the test. + List matchedOwners = ownerDAO.getOwnersByFirstName("AB"); + assertTrue(matchedOwners.isEmpty()); + } + + @Test(expected = PersistenceException.class) + public void shouldUpdateOwnerThrowExceptionWhenOwnerNotExists() throws Exception { + Owner owner = ownerDAO.getOwnerById(1); + owner.setId(123); + ownerDAO.updateOwner(owner); + // HACK: the query actually force Hibernate to execute the UPDATE SQL statement, + // or the @Rollback suppresses the Update SQL statement to fail the test. + // Note, to use getOwnerById() won't force the UPDATE SQL to execute. + assertNull(ownerDAO.getOwnerWithPetsById(123)); + } + + @Test + public void shouldDeleteOwnerWhenOwnerExists() throws Exception { + ownerDAO.deleteOwner(1); + assertEquals(9, ownerDAO.getAllOwners().size()); + } + + @Test(expected = EntityNotFoundException.class) + public void shouldDeleteOwnerThrowExceptionWhenOwnerNotExists() throws Exception { + ownerDAO.deleteOwner(123); + } +} From daa83423c03d210beb21daafb0d59f7626bf6396 Mon Sep 17 00:00:00 2001 From: PunCha Date: Fri, 19 Aug 2016 00:54:41 +0800 Subject: [PATCH 03/29] Add integration test for All Hibernate DAOs --- src/main/java/tk/puncha/dao/PetDAO.java | 6 +- .../puncha/dao/hibernate/HibernatePetDAO.java | 2 +- .../dao/hibernate/HibernateVisitDAO.java | 2 +- src/main/java/tk/puncha/models/Owner.java | 3 +- .../puncha/integration/daos/OwnerDAOTest.java | 1 - .../puncha/integration/daos/PetDAOTest.java | 134 ++++++++++++++++++ .../integration/daos/PetTypeDAOTest.java | 51 +++++++ .../puncha/integration/daos/VisitDAOTest.java | 69 +++++++++ 8 files changed, 261 insertions(+), 7 deletions(-) create mode 100644 src/test/java/tk/puncha/integration/daos/PetDAOTest.java create mode 100644 src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java create mode 100644 src/test/java/tk/puncha/integration/daos/VisitDAOTest.java diff --git a/src/main/java/tk/puncha/dao/PetDAO.java b/src/main/java/tk/puncha/dao/PetDAO.java index 92ec125..df18d2b 100644 --- a/src/main/java/tk/puncha/dao/PetDAO.java +++ b/src/main/java/tk/puncha/dao/PetDAO.java @@ -10,11 +10,11 @@ public interface PetDAO { Pet getPetById(int id); - void deletePetsByOwnerId(int ownerId); + int insertPet(Pet pet); void updatePet(Pet pet); - int insertPet(Pet pet); - void delete(int id); + + void deletePetsByOwnerId(int ownerId); } diff --git a/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java b/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java index 6e646e5..48ab012 100644 --- a/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java +++ b/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java @@ -34,7 +34,7 @@ public Pet getPetById(int petId) { CriteriaQuery cbQuery = cb.createQuery(Pet.class); Root root = cbQuery.from(Pet.class); cbQuery.select(root).where(cb.equal(root.get("id"), petId)); - return em.createQuery(cbQuery).getSingleResult(); + return em.createQuery(cbQuery).getResultList().stream().findFirst().orElse(null); } @Override diff --git a/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java b/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java index 5da814f..be3d8a5 100644 --- a/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java +++ b/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java @@ -22,7 +22,7 @@ public void deleteVisit(int visitId) { @Override public int insertVisit(Visit visit) { - visit = em.merge(visit); + em.persist(visit); return visit.getId(); } diff --git a/src/main/java/tk/puncha/models/Owner.java b/src/main/java/tk/puncha/models/Owner.java index 390ea69..c586da1 100644 --- a/src/main/java/tk/puncha/models/Owner.java +++ b/src/main/java/tk/puncha/models/Owner.java @@ -46,7 +46,8 @@ public Owner() { private String telephone; @OneToMany(mappedBy = "owner", fetch = FetchType.LAZY, - cascade = {CascadeType.REMOVE, CascadeType.PERSIST}) + cascade = {CascadeType.REMOVE, CascadeType.PERSIST}, + orphanRemoval = true) private List pets = new ArrayList<>(); @JsonView({OwnerJsonView.Default.class, PetJsonView.class}) diff --git a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java index 737c1e5..bb6b05b 100644 --- a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java @@ -111,7 +111,6 @@ public void shouldUpdateOwnerSucceededWhenOwnerIsValid() { assertEquals(1, matchedOwners.size()); } - @Test(expected = ConstraintViolationException.class) public void shouldUpdateOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception { Owner owner = ownerDAO.getOwnerById(1); diff --git a/src/test/java/tk/puncha/integration/daos/PetDAOTest.java b/src/test/java/tk/puncha/integration/daos/PetDAOTest.java new file mode 100644 index 0000000..b567a3b --- /dev/null +++ b/src/test/java/tk/puncha/integration/daos/PetDAOTest.java @@ -0,0 +1,134 @@ +package tk.puncha.integration.daos; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; +import tk.puncha.dao.OwnerDAO; +import tk.puncha.dao.PetDAO; +import tk.puncha.dao.PetTypeDAO; +import tk.puncha.models.Pet; + +import javax.persistence.EntityNotFoundException; +import javax.persistence.PersistenceException; +import javax.validation.ConstraintViolationException; +import java.util.List; + +import static org.junit.Assert.*; + +@ActiveProfiles("hibernate,mysql") +@TestPropertySource(locations = {"/test.properties"}) +@AutoConfigureTestDatabase +@Transactional +@Rollback +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +@RunWith(SpringJUnit4ClassRunner.class) +public class PetDAOTest { + @Autowired + private PetDAO petDAO; + @Autowired + private OwnerDAO ownerDAO; + @Autowired + private PetTypeDAO petTypeDAO; + + public void forceFlush() { + petDAO.getAllPets(); + } + + @Test + public void shouldGetAllPetsReturnAllPetsList() throws Exception { + List Pets = petDAO.getAllPets(); + assertEquals(13, Pets.size()); + } + + @Test + public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { + Pet pet = petDAO.getPetById(1); + assertNotNull(pet); + assertEquals(1, pet.getId()); + } + + @Test + public void shouldGetPetByIdReturnNullWhenPetNotExists() throws Exception { + Pet pet = petDAO.getPetById(-1); + assertNull(pet); + } + + @Test + public void shouldInsertPetSuccessWhenPetIsValid() throws Exception { + Pet pet = new Pet(); + pet.setName("puncha"); + pet.setType(petTypeDAO.getTypeById(1)); + pet.setOwner(ownerDAO.getOwnerById(1)); + int id = petDAO.insertPet(pet); + assertNotEquals(-1, id); + } + + @Test(expected = ConstraintViolationException.class) + public void shouldInsertPetThrowExceptionWhenPetIsInvalid() throws Exception { + Pet Pet = new Pet(); + petDAO.insertPet(Pet); + } + + @Test(expected = PersistenceException.class) + public void shouldInsertPetThrowExceptionWhenPetIdIsNotDefault() throws Exception { + Pet Pet = new Pet(); + Pet.setId(123); + petDAO.insertPet(Pet); + } + + @Test + public void shouldUpdatePetSucceededWhenPetIsValid() { + Pet pet = petDAO.getPetById(1); + pet.setName("puncha"); + petDAO.updatePet(pet); + forceFlush(); + } + + + @Test(expected = ConstraintViolationException.class) + public void shouldUpdatePetThrowExceptionWhenPetIsInvalid() throws Exception { + Pet pet = petDAO.getPetById(1); + pet.setName("AB"); + petDAO.updatePet(pet); + forceFlush(); + } + + @Test(expected = PersistenceException.class) + public void shouldUpdatePetThrowExceptionWhenPetNotExists() throws Exception { + Pet pet = petDAO.getPetById(1); + pet.setId(123); + petDAO.updatePet(pet); + forceFlush(); + + } + + @Test + public void shouldDeletePetWhenPetExists() throws Exception { + petDAO.delete(1); + assertEquals(12, petDAO.getAllPets().size()); + } + + @Test(expected = EntityNotFoundException.class) + public void shouldDeletePetThrowExceptionWhenPetNotExists() throws Exception { + petDAO.delete(123); + } + + @Test + public void shouldDeletePetsByOwnerIdDeletePetsWhenOwnerExists() { + petDAO.deletePetsByOwnerId(3); // Eduardo has two pets + assertEquals(11, petDAO.getAllPets().size()); + } + + + @Test(expected = EntityNotFoundException.class) + public void shouldDeletePetsByOwnerIdThrowExceptionWhenOwnerNotExists() { + petDAO.deletePetsByOwnerId(123); + } +} diff --git a/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java b/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java new file mode 100644 index 0000000..6779fde --- /dev/null +++ b/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java @@ -0,0 +1,51 @@ +package tk.puncha.integration.daos; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; +import tk.puncha.dao.PetTypeDAO; +import tk.puncha.models.PetType; + +import java.util.List; + +import static org.junit.Assert.*; + +@ActiveProfiles("hibernate,mysql") +@TestPropertySource(locations = {"/test.properties"}) +@AutoConfigureTestDatabase +@Transactional +@Rollback +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +@RunWith(SpringJUnit4ClassRunner.class) +public class PetTypeDAOTest { + @Autowired + private PetTypeDAO petTypeDAO; + + @Test + public void shouldGetAllPetTypesReturnAllPetTypesList() throws Exception { + List Pets = petTypeDAO.getAllTypes(); + assertEquals(6, Pets.size()); + } + + @Test + public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { + PetType petType = petTypeDAO.getTypeById(1); + assertNotNull(petType); + assertEquals(1, petType.getId()); + assertEquals("cat", petType.getName()); + } + + @Test + public void shouldGetPetByIdReturnNullWhenPetNotExists() throws Exception { + PetType petType = petTypeDAO.getTypeById(-1); + assertNull(petType); + } + +} diff --git a/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java b/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java new file mode 100644 index 0000000..7b63b86 --- /dev/null +++ b/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java @@ -0,0 +1,69 @@ +package tk.puncha.integration.daos; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.Rollback; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; +import tk.puncha.dao.PetDAO; +import tk.puncha.dao.VisitDAO; +import tk.puncha.models.Visit; + +import javax.persistence.EntityNotFoundException; +import javax.persistence.PersistenceException; +import javax.validation.ConstraintViolationException; +import java.sql.Date; + +import static org.junit.Assert.assertNotEquals; + +@ActiveProfiles("hibernate,mysql") +@TestPropertySource(locations = {"/test.properties"}) +@AutoConfigureTestDatabase +@Transactional +@Rollback +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +@RunWith(SpringJUnit4ClassRunner.class) +public class VisitDAOTest { + @Autowired + private PetDAO petDAO; + @Autowired + private VisitDAO visitDAO; + + @Test + public void shouldInsertVisitSuccessWhenVisitIsValid() throws Exception { + Visit visit = new Visit(); + visit.setVisitDate(Date.valueOf("2011-08-09")); + visit.setDescription("A test visit"); + visit.setPet(petDAO.getPetById(1)); + int id = visitDAO.insertVisit(visit); + assertNotEquals(-1, id); + } + + @Test(expected = ConstraintViolationException.class) + public void shouldInsertVisitThrowExceptionWhenVisitIsInvalid() throws Exception { + Visit Visit = new Visit(); + visitDAO.insertVisit(Visit); + } + + @Test(expected = PersistenceException.class) + public void shouldInsertVisitThrowExceptionWhenVisitIdIsNotDefault() throws Exception { + Visit Visit = new Visit(); + Visit.setId(123); + visitDAO.insertVisit(Visit); + } + + @Test + public void shouldDeleteVisitWhenVisitExists() throws Exception { + visitDAO.deleteVisit(1); + } + + @Test(expected = EntityNotFoundException.class) + public void shouldDeleteVisitThrowExceptionWhenVisitNotExists() throws Exception { + visitDAO.deleteVisit(123); + } +} From 92c35bead69e06dd421a667a8a9cfc87a6b66ca5 Mon Sep 17 00:00:00 2001 From: PunCha Date: Fri, 19 Aug 2016 01:10:41 +0800 Subject: [PATCH 04/29] Unify DAO method naming convention: getAll, getById, insert, update, deleteById... --- src/main/java/tk/puncha/dao/OwnerDAO.java | 14 +++--- src/main/java/tk/puncha/dao/PetDAO.java | 12 ++--- src/main/java/tk/puncha/dao/PetTypeDAO.java | 5 +- src/main/java/tk/puncha/dao/VisitDAO.java | 5 +- .../dao/hibernate/HibernateOwnerDAO.java | 15 +++--- .../puncha/dao/hibernate/HibernatePetDAO.java | 12 ++--- .../dao/hibernate/HibernatePetTypeDAO.java | 4 +- .../dao/hibernate/HibernateVisitDAO.java | 4 +- .../java/tk/puncha/dao/jdbc/JdbcOwnerDAO.java | 14 +++--- .../java/tk/puncha/dao/jdbc/JdbcPetDAO.java | 12 ++--- .../tk/puncha/dao/jdbc/JdbcPetTypeDAO.java | 4 +- .../puncha/dao/mybatis/MyBatisOwnerDAO.java | 14 +++--- .../tk/puncha/dao/mybatis/MyBatisPetDAO.java | 12 ++--- .../puncha/dao/mybatis/MyBatisPetTypeDAO.java | 4 +- .../puncha/repositories/OwnerRepository.java | 14 +++--- .../tk/puncha/repositories/PetRepository.java | 14 +++--- .../repositories/PetTypeRepository.java | 4 +- .../puncha/repositories/VisitRepository.java | 4 +- .../puncha/integration/daos/OwnerDAOTest.java | 46 +++++++++---------- .../puncha/integration/daos/PetDAOTest.java | 42 ++++++++--------- .../integration/daos/PetTypeDAOTest.java | 6 +-- .../puncha/integration/daos/VisitDAOTest.java | 12 ++--- .../controllers/OwnerControllerTests.java | 6 +-- .../repositories/OwnerRepositoryTests.java | 4 +- 24 files changed, 142 insertions(+), 141 deletions(-) diff --git a/src/main/java/tk/puncha/dao/OwnerDAO.java b/src/main/java/tk/puncha/dao/OwnerDAO.java index ce6f3f3..581298d 100644 --- a/src/main/java/tk/puncha/dao/OwnerDAO.java +++ b/src/main/java/tk/puncha/dao/OwnerDAO.java @@ -6,17 +6,17 @@ public interface OwnerDAO { - List getAllOwners(); + List getAll(); - List getOwnersByFirstName(String firstName); + List findByFirstName(String firstName); - Owner getOwnerById(int ownerId); + Owner getById(int ownerId); - Owner getOwnerWithPetsById(int ownerId); + Owner getByIdWithPets(int ownerId); - int insertOwner(Owner owner); + int insert(Owner owner); - void updateOwner(Owner owner); + void update(Owner owner); - void deleteOwner(int id); + void deleteById(int id); } diff --git a/src/main/java/tk/puncha/dao/PetDAO.java b/src/main/java/tk/puncha/dao/PetDAO.java index df18d2b..08b27f1 100644 --- a/src/main/java/tk/puncha/dao/PetDAO.java +++ b/src/main/java/tk/puncha/dao/PetDAO.java @@ -6,15 +6,15 @@ public interface PetDAO { - List getAllPets(); + List getAll(); - Pet getPetById(int id); + Pet getById(int id); - int insertPet(Pet pet); + int insert(Pet pet); - void updatePet(Pet pet); + void update(Pet pet); - void delete(int id); + void deleteById(int id); - void deletePetsByOwnerId(int ownerId); + void deleteByOwnerId(int ownerId); } diff --git a/src/main/java/tk/puncha/dao/PetTypeDAO.java b/src/main/java/tk/puncha/dao/PetTypeDAO.java index 23aeacd..51572be 100644 --- a/src/main/java/tk/puncha/dao/PetTypeDAO.java +++ b/src/main/java/tk/puncha/dao/PetTypeDAO.java @@ -5,7 +5,8 @@ import java.util.List; public interface PetTypeDAO { - List getAllTypes(); - PetType getTypeById(int id); + List getAll(); + + PetType getById(int id); } diff --git a/src/main/java/tk/puncha/dao/VisitDAO.java b/src/main/java/tk/puncha/dao/VisitDAO.java index 6c4ac4e..0132397 100644 --- a/src/main/java/tk/puncha/dao/VisitDAO.java +++ b/src/main/java/tk/puncha/dao/VisitDAO.java @@ -3,7 +3,8 @@ import tk.puncha.models.Visit; public interface VisitDAO { - void deleteVisit(int visitId); - int insertVisit(Visit visit); + int insert(Visit visit); + + void deleteById(int visitId); } diff --git a/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java b/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java index 25351ed..3a35767 100644 --- a/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java +++ b/src/main/java/tk/puncha/dao/hibernate/HibernateOwnerDAO.java @@ -7,7 +7,6 @@ import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; import tk.puncha.controllers.PetController; import tk.puncha.dao.OwnerDAO; import tk.puncha.models.Owner; @@ -28,7 +27,7 @@ public class HibernateOwnerDAO implements OwnerDAO { private EntityManager em; @Override - public List getAllOwners() { + public List getAll() { return em.createQuery("select distinct o from Owner o", Owner.class) .setHint(HINT_FETCHGRAPH, em.getEntityGraph("graph.Owners.lazyPets")) .getResultList(); @@ -36,7 +35,7 @@ public List getAllOwners() { @Override @SuppressWarnings("unchecked") - public List getOwnersByFirstName(String firstName) { + public List findByFirstName(String firstName) { Owner owner = new Owner(); owner.setFirstName(firstName); return em.unwrap(Session.class).createCriteria(Owner.class) @@ -45,11 +44,11 @@ public List getOwnersByFirstName(String firstName) { } @Override - public Owner getOwnerById(int ownerId) { + public Owner getById(int ownerId) { return em.find(Owner.class, ownerId); } - public Owner getOwnerWithPetsById(int ownerId) { + public Owner getByIdWithPets(int ownerId) { String query = "select owner from Owner owner left join fetch owner.pets where owner.id = :ownerId"; return em.createQuery(query, Owner.class) .setParameter("ownerId", ownerId) @@ -57,18 +56,18 @@ public Owner getOwnerWithPetsById(int ownerId) { } @Override - public int insertOwner(Owner owner) { + public int insert(Owner owner) { em.persist(owner); return owner.getId(); } @Override - public void updateOwner(Owner owner) { + public void update(Owner owner) { em.merge(owner); } @Override - public void deleteOwner(int id) { + public void deleteById(int id) { Owner reference = em.getReference(Owner.class, id); logger.error("reference got!"); em.remove(reference); diff --git a/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java b/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java index 48ab012..fd7c479 100644 --- a/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java +++ b/src/main/java/tk/puncha/dao/hibernate/HibernatePetDAO.java @@ -21,7 +21,7 @@ public class HibernatePetDAO implements PetDAO { private EntityManager em; @Override - public List getAllPets() { + public List getAll() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cbQuery = cb.createQuery(Pet.class); cbQuery.select(cbQuery.from(Pet.class)); @@ -29,7 +29,7 @@ public List getAllPets() { } @Override - public Pet getPetById(int petId) { + public Pet getById(int petId) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cbQuery = cb.createQuery(Pet.class); Root root = cbQuery.from(Pet.class); @@ -38,18 +38,18 @@ public Pet getPetById(int petId) { } @Override - public int insertPet(Pet pet) { + public int insert(Pet pet) { em.persist(pet); return pet.getId(); } @Override - public void updatePet(Pet pet) { + public void update(Pet pet) { em.merge(pet); } @Override - public void deletePetsByOwnerId(int ownerId) { + public void deleteByOwnerId(int ownerId) { // TODO: the logic should be in OwnerDAO Owner owner = em.getReference(Owner.class, ownerId); owner.getPets().clear(); @@ -57,7 +57,7 @@ public void deletePetsByOwnerId(int ownerId) { } @Override - public void delete(int id) { + public void deleteById(int id) { Pet pet = em.getReference(Pet.class, id); em.remove(pet); } diff --git a/src/main/java/tk/puncha/dao/hibernate/HibernatePetTypeDAO.java b/src/main/java/tk/puncha/dao/hibernate/HibernatePetTypeDAO.java index bccde6b..ac01230 100644 --- a/src/main/java/tk/puncha/dao/hibernate/HibernatePetTypeDAO.java +++ b/src/main/java/tk/puncha/dao/hibernate/HibernatePetTypeDAO.java @@ -17,13 +17,13 @@ public class HibernatePetTypeDAO implements PetTypeDAO { private EntityManager em; @Override - public List getAllTypes() { + public List getAll() { String query = "select petType from PetType petType"; return em.createQuery(query, PetType.class).getResultList(); } @Override - public PetType getTypeById(int id) { + public PetType getById(int id) { return em.find(PetType.class, id); } } diff --git a/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java b/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java index be3d8a5..ef4fbb8 100644 --- a/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java +++ b/src/main/java/tk/puncha/dao/hibernate/HibernateVisitDAO.java @@ -16,12 +16,12 @@ public class HibernateVisitDAO implements VisitDAO { private EntityManager em; @Override - public void deleteVisit(int visitId) { + public void deleteById(int visitId) { em.remove(em.getReference(Visit.class, visitId)); } @Override - public int insertVisit(Visit visit) { + public int insert(Visit visit) { em.persist(visit); return visit.getId(); } diff --git a/src/main/java/tk/puncha/dao/jdbc/JdbcOwnerDAO.java b/src/main/java/tk/puncha/dao/jdbc/JdbcOwnerDAO.java index d3288eb..2d57519 100644 --- a/src/main/java/tk/puncha/dao/jdbc/JdbcOwnerDAO.java +++ b/src/main/java/tk/puncha/dao/jdbc/JdbcOwnerDAO.java @@ -45,25 +45,25 @@ public JdbcOwnerDAO(DataSource dataSource) { }; } - public List getAllOwners() { + public List getAll() { return this.getJdbcTemplate().query(SQL_QUERY_ALL, ownerRowMapper); } @Override - public List getOwnersByFirstName(String firstName) { + public List findByFirstName(String firstName) { throw new RuntimeException("Not implemented"); } - public Owner getOwnerById(int ownerId) { + public Owner getById(int ownerId) { return this.getJdbcTemplate().queryForObject(SQL_QUERY_BY_ID, ownerRowMapper, ownerId); } @Override - public Owner getOwnerWithPetsById(int ownerId) { + public Owner getByIdWithPets(int ownerId) { throw new RuntimeException("Not implemented yet."); } - public int insertOwner(Owner owner) { + public int insert(Owner owner) { HashMap parameters = new HashMap<>(5); parameters.put("first_name", owner.getFirstName()); parameters.put("last_name", owner.getLastName()); @@ -75,7 +75,7 @@ public int insertOwner(Owner owner) { return owner.getId(); } - public void updateOwner(Owner owner) { + public void update(Owner owner) { this.getJdbcTemplate().update( SQL_UPDATE, owner.getFirstName(), owner.getLastName(), owner.getAddress(), owner.getCity(), owner.getTelephone(), @@ -86,7 +86,7 @@ public void updateOwner(Owner owner) { // the caller should make sure the owner's pets are // deleted. @Transactional - public void deleteOwner(int id) { + public void deleteById(int id) { this.getJdbcTemplate().update(SQL_DELETE_BY_ID, id); } diff --git a/src/main/java/tk/puncha/dao/jdbc/JdbcPetDAO.java b/src/main/java/tk/puncha/dao/jdbc/JdbcPetDAO.java index 0b0ff53..c1df1d5 100644 --- a/src/main/java/tk/puncha/dao/jdbc/JdbcPetDAO.java +++ b/src/main/java/tk/puncha/dao/jdbc/JdbcPetDAO.java @@ -42,23 +42,23 @@ public JdbcPetDAO(DataSource dataSource) { } @Override - public List getAllPets() { + public List getAll() { return this.getJdbcTemplate().query(SQL_QUERY_ALL, rowMapper); } @Override - public Pet getPetById(int id) { + public Pet getById(int id) { return this.getJdbcTemplate().queryForObject(SQL_QUERY_BY_ID, rowMapper, id); } @Override @Transactional - public void deletePetsByOwnerId(int ownerId) { + public void deleteByOwnerId(int ownerId) { this.getJdbcTemplate().update(SQL_DELETE_BY_OWNER, ownerId); } @Override - public void updatePet(Pet pet) { + public void update(Pet pet) { // TODO: FIX ME throw new RuntimeException(); // this.getJdbcTemplate().update( @@ -66,7 +66,7 @@ public void updatePet(Pet pet) { } @Override - public int insertPet(Pet pet) { + public int insert(Pet pet) { // TODO: FIX ME throw new RuntimeException(); // HashMap parameters = new HashMap<>(); @@ -80,7 +80,7 @@ public int insertPet(Pet pet) { } @Override - public void delete(int id) { + public void deleteById(int id) { this.getJdbcTemplate().update(SQL_DELETE_BY_ID, id); } } diff --git a/src/main/java/tk/puncha/dao/jdbc/JdbcPetTypeDAO.java b/src/main/java/tk/puncha/dao/jdbc/JdbcPetTypeDAO.java index 66041f8..d05b91a 100644 --- a/src/main/java/tk/puncha/dao/jdbc/JdbcPetTypeDAO.java +++ b/src/main/java/tk/puncha/dao/jdbc/JdbcPetTypeDAO.java @@ -31,13 +31,13 @@ public JdbcPetTypeDAO(DataSource dataSource) { } @Override - public List getAllTypes() { + public List getAll() { return this.getJdbcTemplate().query(SQL_QUERY_ALL, rowMapper); } @Override - public PetType getTypeById(int id) { + public PetType getById(int id) { return this.getJdbcTemplate().queryForObject(SQL_QUERY_BY_ID, rowMapper, id); } } diff --git a/src/main/java/tk/puncha/dao/mybatis/MyBatisOwnerDAO.java b/src/main/java/tk/puncha/dao/mybatis/MyBatisOwnerDAO.java index d9b8944..d3f6169 100644 --- a/src/main/java/tk/puncha/dao/mybatis/MyBatisOwnerDAO.java +++ b/src/main/java/tk/puncha/dao/mybatis/MyBatisOwnerDAO.java @@ -17,37 +17,37 @@ public class MyBatisOwnerDAO implements OwnerDAO { private OwnerMapper mapper; @Override - public List getAllOwners() { + public List getAll() { return mapper.getAllOwners(); } @Override - public List getOwnersByFirstName(String firstName) { + public List findByFirstName(String firstName) { throw new RuntimeException("Not implemented"); } @Override - public Owner getOwnerById(int ownerId) { + public Owner getById(int ownerId) { return mapper.getOwnerById(ownerId); } @Override - public Owner getOwnerWithPetsById(int ownerId) { + public Owner getByIdWithPets(int ownerId) { return mapper.getOwnerWithPetsById(ownerId); } @Override - public int insertOwner(Owner owner) { + public int insert(Owner owner) { return mapper.insertOwner(owner); } @Override - public void updateOwner(Owner owner) { + public void update(Owner owner) { mapper.updateOwner(owner); } @Override - public void deleteOwner(int id) { + public void deleteById(int id) { mapper.deleteOwner(id); } } diff --git a/src/main/java/tk/puncha/dao/mybatis/MyBatisPetDAO.java b/src/main/java/tk/puncha/dao/mybatis/MyBatisPetDAO.java index cc6870a..3627a07 100644 --- a/src/main/java/tk/puncha/dao/mybatis/MyBatisPetDAO.java +++ b/src/main/java/tk/puncha/dao/mybatis/MyBatisPetDAO.java @@ -18,33 +18,33 @@ public class MyBatisPetDAO implements PetDAO { private PetMapper mapper; @Override - public List getAllPets() { + public List getAll() { return mapper.getAllPets(); } @Override - public Pet getPetById(int petId) { + public Pet getById(int petId) { return mapper.getPetById(petId); } @Override - public int insertPet(Pet pet) { + public int insert(Pet pet) { return mapper.insertPet(pet); } @Override - public void updatePet(Pet pet) { + public void update(Pet pet) { mapper.updatePet(pet); } @Override - public void deletePetsByOwnerId(int ownerId) { + public void deleteByOwnerId(int ownerId) { mapper.deletePetsByOwnerId(ownerId); } @Override @Transactional - public void delete(int id) { + public void deleteById(int id) { mapper.delete(id); } diff --git a/src/main/java/tk/puncha/dao/mybatis/MyBatisPetTypeDAO.java b/src/main/java/tk/puncha/dao/mybatis/MyBatisPetTypeDAO.java index e33cbd2..4178036 100644 --- a/src/main/java/tk/puncha/dao/mybatis/MyBatisPetTypeDAO.java +++ b/src/main/java/tk/puncha/dao/mybatis/MyBatisPetTypeDAO.java @@ -17,12 +17,12 @@ public class MyBatisPetTypeDAO implements PetTypeDAO { private PetTypeMapper mapper; @Override - public List getAllTypes() { + public List getAll() { return mapper.getAllTypes(); } @Override - public PetType getTypeById(int id) { + public PetType getById(int id) { return mapper.getTypeById(id); } } diff --git a/src/main/java/tk/puncha/repositories/OwnerRepository.java b/src/main/java/tk/puncha/repositories/OwnerRepository.java index 18bfe10..ac1f9f8 100644 --- a/src/main/java/tk/puncha/repositories/OwnerRepository.java +++ b/src/main/java/tk/puncha/repositories/OwnerRepository.java @@ -20,35 +20,35 @@ public OwnerRepository(OwnerDAO ownerDAO) { @Transactional public List getAllOwners() { - return ownerDAO.getAllOwners(); + return ownerDAO.getAll(); } public List getOwnersByFirstName(String firstName){ - return ownerDAO.getOwnersByFirstName(firstName); + return ownerDAO.findByFirstName(firstName); } @Transactional public Owner getOwnerById(int ownerId) { - return ownerDAO.getOwnerById(ownerId); + return ownerDAO.getById(ownerId); } @Transactional public Owner getOwnerWithPetsById(int ownerId) { - return ownerDAO.getOwnerWithPetsById(ownerId); + return ownerDAO.getByIdWithPets(ownerId); } @Transactional public void insertOwner(Owner owner) { - ownerDAO.insertOwner(owner); + ownerDAO.insert(owner); } @Transactional public void updateOwner(Owner owner) { - ownerDAO.updateOwner(owner); + ownerDAO.update(owner); } @Transactional public void deleteOwner(int ownerId) { - ownerDAO.deleteOwner(ownerId); + ownerDAO.deleteById(ownerId); } } diff --git a/src/main/java/tk/puncha/repositories/PetRepository.java b/src/main/java/tk/puncha/repositories/PetRepository.java index 579f816..6435fd9 100644 --- a/src/main/java/tk/puncha/repositories/PetRepository.java +++ b/src/main/java/tk/puncha/repositories/PetRepository.java @@ -26,33 +26,33 @@ public PetRepository(PetDAO petDAO, PetTypeDAO petTypeDAO) { @Transactional(readOnly = true) public List getAllPets() { - return petDAO.getAllPets(); + return petDAO.getAll(); } @Transactional(readOnly = true) public Pet getPetById(int id) { - return petDAO.getPetById(id); + return petDAO.getById(id); } public void updatePet(Pet pet) { - petDAO.updatePet(pet); + petDAO.update(pet); } public int insertPet(Pet pet) { - return petDAO.insertPet(pet); + return petDAO.insert(pet); } public void delete(int id) { - petDAO.delete(id); + petDAO.deleteById(id); } @Transactional(readOnly = true) public List getAllTypes() { - return petTypeDAO.getAllTypes(); + return petTypeDAO.getAll(); } public void deletePetsByOwnerId(int ownerId) { - petDAO.deletePetsByOwnerId(ownerId); + petDAO.deleteByOwnerId(ownerId); } } diff --git a/src/main/java/tk/puncha/repositories/PetTypeRepository.java b/src/main/java/tk/puncha/repositories/PetTypeRepository.java index 946595d..5651cd0 100644 --- a/src/main/java/tk/puncha/repositories/PetTypeRepository.java +++ b/src/main/java/tk/puncha/repositories/PetTypeRepository.java @@ -18,10 +18,10 @@ public PetTypeRepository(PetTypeDAO petTypeDAO) { } public List getAllTypes() { - return petTypeDAO.getAllTypes(); + return petTypeDAO.getAll(); } public PetType getPetTypeById(int id) { - return petTypeDAO.getTypeById(id); + return petTypeDAO.getById(id); } } diff --git a/src/main/java/tk/puncha/repositories/VisitRepository.java b/src/main/java/tk/puncha/repositories/VisitRepository.java index e5cadee..01e0d3c 100644 --- a/src/main/java/tk/puncha/repositories/VisitRepository.java +++ b/src/main/java/tk/puncha/repositories/VisitRepository.java @@ -18,11 +18,11 @@ public VisitRepository(VisitDAO visitDAO) { @Transactional public int insertVisit(Visit visit) { - return visitDAO.insertVisit(visit); + return visitDAO.insert(visit); } @Transactional public void delete(int id) { - visitDAO.deleteVisit(id); + visitDAO.deleteById(id); } } diff --git a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java index bb6b05b..994feab 100644 --- a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java @@ -35,13 +35,13 @@ public class OwnerDAOTest { @Test public void shouldGetAllOwnersReturnAllOwnersList() throws Exception { - List owners = ownerDAO.getAllOwners(); + List owners = ownerDAO.getAll(); assertEquals(10, owners.size()); } @Test public void shouldGetOwnerByIdReturnOwnerWhenOwnerExists() throws Exception { - Owner owner = ownerDAO.getOwnerById(1); + Owner owner = ownerDAO.getById(1); assertNotNull(owner); assertEquals(1, owner.getId()); assertFalse(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); @@ -49,13 +49,13 @@ public void shouldGetOwnerByIdReturnOwnerWhenOwnerExists() throws Exception { @Test public void shouldGetOwnerByIdReturnNullWhenOwnerNotExists() throws Exception { - Owner owner = ownerDAO.getOwnerById(-1); + Owner owner = ownerDAO.getById(-1); assertNull(owner); } @Test public void shouldGetOwnerWithPetsByIdReturnOwnerWithPetsWhenOwnerExists() throws Exception { - Owner owner = ownerDAO.getOwnerWithPetsById(1); + Owner owner = ownerDAO.getByIdWithPets(1); assertNotNull(owner); assertEquals(1, owner.getId()); assertTrue(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); @@ -63,19 +63,19 @@ public void shouldGetOwnerWithPetsByIdReturnOwnerWithPetsWhenOwnerExists() throw @Test public void shouldGetOwnerWithPetsByIdReturnNullWhenOwnerNotExists() throws Exception { - Owner owner = ownerDAO.getOwnerWithPetsById(-1); + Owner owner = ownerDAO.getByIdWithPets(-1); assertNull(owner); } @Test public void shouldGetOwnersByFirstNameReturnMatchedOwnersList() throws Exception { - List owners = ownerDAO.getOwnersByFirstName("eT"); + List owners = ownerDAO.findByFirstName("eT"); assertEquals(2, owners.size()); } @Test public void shouldGetOwnersByFirstNameReturnEmptyListWhenOnMatchedOwners() throws Exception { - List owners = ownerDAO.getOwnersByFirstName("puncha"); + List owners = ownerDAO.findByFirstName("puncha"); assertTrue(owners.isEmpty()); } @@ -85,62 +85,62 @@ public void shouldInsertOwnerSuccessWhenOwnerIsValid() throws Exception { owner.setFirstName("puncha"); owner.setLastName("feng"); owner.setAddress("sample address"); - int id = ownerDAO.insertOwner(owner); + int id = ownerDAO.insert(owner); assertNotEquals(-1, id); } @Test(expected = ConstraintViolationException.class) public void shouldInsertOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception { Owner owner = new Owner(); - ownerDAO.insertOwner(owner); + ownerDAO.insert(owner); } @Test(expected = PersistenceException.class) public void shouldInsertOwnerThrowExceptionWhenOwnerIdIsNotDefault() throws Exception { Owner owner = new Owner(); owner.setId(123); - ownerDAO.insertOwner(owner); + ownerDAO.insert(owner); } @Test public void shouldUpdateOwnerSucceededWhenOwnerIsValid() { - Owner owner = ownerDAO.getOwnerById(1); + Owner owner = ownerDAO.getById(1); owner.setFirstName("puncha"); - ownerDAO.updateOwner(owner); - List matchedOwners = ownerDAO.getOwnersByFirstName("puncha"); + ownerDAO.update(owner); + List matchedOwners = ownerDAO.findByFirstName("puncha"); assertEquals(1, matchedOwners.size()); } @Test(expected = ConstraintViolationException.class) public void shouldUpdateOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception { - Owner owner = ownerDAO.getOwnerById(1); + Owner owner = ownerDAO.getById(1); owner.setFirstName("AB"); - ownerDAO.updateOwner(owner); + ownerDAO.update(owner); // HACK: the query actually force Hibernate to execute the UPDATE SQL statement, // or the @Rollback suppresses the Update SQL statement to fail the test. - List matchedOwners = ownerDAO.getOwnersByFirstName("AB"); + List matchedOwners = ownerDAO.findByFirstName("AB"); assertTrue(matchedOwners.isEmpty()); } @Test(expected = PersistenceException.class) public void shouldUpdateOwnerThrowExceptionWhenOwnerNotExists() throws Exception { - Owner owner = ownerDAO.getOwnerById(1); + Owner owner = ownerDAO.getById(1); owner.setId(123); - ownerDAO.updateOwner(owner); + ownerDAO.update(owner); // HACK: the query actually force Hibernate to execute the UPDATE SQL statement, // or the @Rollback suppresses the Update SQL statement to fail the test. - // Note, to use getOwnerById() won't force the UPDATE SQL to execute. - assertNull(ownerDAO.getOwnerWithPetsById(123)); + // Note, to use getById() won't force the UPDATE SQL to execute. + assertNull(ownerDAO.getByIdWithPets(123)); } @Test public void shouldDeleteOwnerWhenOwnerExists() throws Exception { - ownerDAO.deleteOwner(1); - assertEquals(9, ownerDAO.getAllOwners().size()); + ownerDAO.deleteById(1); + assertEquals(9, ownerDAO.getAll().size()); } @Test(expected = EntityNotFoundException.class) public void shouldDeleteOwnerThrowExceptionWhenOwnerNotExists() throws Exception { - ownerDAO.deleteOwner(123); + ownerDAO.deleteById(123); } } diff --git a/src/test/java/tk/puncha/integration/daos/PetDAOTest.java b/src/test/java/tk/puncha/integration/daos/PetDAOTest.java index b567a3b..aedcf48 100644 --- a/src/test/java/tk/puncha/integration/daos/PetDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/PetDAOTest.java @@ -38,25 +38,25 @@ public class PetDAOTest { private PetTypeDAO petTypeDAO; public void forceFlush() { - petDAO.getAllPets(); + petDAO.getAll(); } @Test public void shouldGetAllPetsReturnAllPetsList() throws Exception { - List Pets = petDAO.getAllPets(); + List Pets = petDAO.getAll(); assertEquals(13, Pets.size()); } @Test public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { - Pet pet = petDAO.getPetById(1); + Pet pet = petDAO.getById(1); assertNotNull(pet); assertEquals(1, pet.getId()); } @Test public void shouldGetPetByIdReturnNullWhenPetNotExists() throws Exception { - Pet pet = petDAO.getPetById(-1); + Pet pet = petDAO.getById(-1); assertNull(pet); } @@ -64,71 +64,71 @@ public void shouldGetPetByIdReturnNullWhenPetNotExists() throws Exception { public void shouldInsertPetSuccessWhenPetIsValid() throws Exception { Pet pet = new Pet(); pet.setName("puncha"); - pet.setType(petTypeDAO.getTypeById(1)); - pet.setOwner(ownerDAO.getOwnerById(1)); - int id = petDAO.insertPet(pet); + pet.setType(petTypeDAO.getById(1)); + pet.setOwner(ownerDAO.getById(1)); + int id = petDAO.insert(pet); assertNotEquals(-1, id); } @Test(expected = ConstraintViolationException.class) public void shouldInsertPetThrowExceptionWhenPetIsInvalid() throws Exception { Pet Pet = new Pet(); - petDAO.insertPet(Pet); + petDAO.insert(Pet); } @Test(expected = PersistenceException.class) public void shouldInsertPetThrowExceptionWhenPetIdIsNotDefault() throws Exception { Pet Pet = new Pet(); Pet.setId(123); - petDAO.insertPet(Pet); + petDAO.insert(Pet); } @Test public void shouldUpdatePetSucceededWhenPetIsValid() { - Pet pet = petDAO.getPetById(1); + Pet pet = petDAO.getById(1); pet.setName("puncha"); - petDAO.updatePet(pet); + petDAO.update(pet); forceFlush(); } @Test(expected = ConstraintViolationException.class) public void shouldUpdatePetThrowExceptionWhenPetIsInvalid() throws Exception { - Pet pet = petDAO.getPetById(1); + Pet pet = petDAO.getById(1); pet.setName("AB"); - petDAO.updatePet(pet); + petDAO.update(pet); forceFlush(); } @Test(expected = PersistenceException.class) public void shouldUpdatePetThrowExceptionWhenPetNotExists() throws Exception { - Pet pet = petDAO.getPetById(1); + Pet pet = petDAO.getById(1); pet.setId(123); - petDAO.updatePet(pet); + petDAO.update(pet); forceFlush(); } @Test public void shouldDeletePetWhenPetExists() throws Exception { - petDAO.delete(1); - assertEquals(12, petDAO.getAllPets().size()); + petDAO.deleteById(1); + assertEquals(12, petDAO.getAll().size()); } @Test(expected = EntityNotFoundException.class) public void shouldDeletePetThrowExceptionWhenPetNotExists() throws Exception { - petDAO.delete(123); + petDAO.deleteById(123); } @Test public void shouldDeletePetsByOwnerIdDeletePetsWhenOwnerExists() { - petDAO.deletePetsByOwnerId(3); // Eduardo has two pets - assertEquals(11, petDAO.getAllPets().size()); + petDAO.deleteByOwnerId(3); // Eduardo has two pets + assertEquals(11, petDAO.getAll().size()); } @Test(expected = EntityNotFoundException.class) public void shouldDeletePetsByOwnerIdThrowExceptionWhenOwnerNotExists() { - petDAO.deletePetsByOwnerId(123); + petDAO.deleteByOwnerId(123); } } diff --git a/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java b/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java index 6779fde..25331da 100644 --- a/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java @@ -30,13 +30,13 @@ public class PetTypeDAOTest { @Test public void shouldGetAllPetTypesReturnAllPetTypesList() throws Exception { - List Pets = petTypeDAO.getAllTypes(); + List Pets = petTypeDAO.getAll(); assertEquals(6, Pets.size()); } @Test public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { - PetType petType = petTypeDAO.getTypeById(1); + PetType petType = petTypeDAO.getById(1); assertNotNull(petType); assertEquals(1, petType.getId()); assertEquals("cat", petType.getName()); @@ -44,7 +44,7 @@ public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { @Test public void shouldGetPetByIdReturnNullWhenPetNotExists() throws Exception { - PetType petType = petTypeDAO.getTypeById(-1); + PetType petType = petTypeDAO.getById(-1); assertNull(petType); } diff --git a/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java b/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java index 7b63b86..90e20e8 100644 --- a/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java @@ -39,31 +39,31 @@ public void shouldInsertVisitSuccessWhenVisitIsValid() throws Exception { Visit visit = new Visit(); visit.setVisitDate(Date.valueOf("2011-08-09")); visit.setDescription("A test visit"); - visit.setPet(petDAO.getPetById(1)); - int id = visitDAO.insertVisit(visit); + visit.setPet(petDAO.getById(1)); + int id = visitDAO.insert(visit); assertNotEquals(-1, id); } @Test(expected = ConstraintViolationException.class) public void shouldInsertVisitThrowExceptionWhenVisitIsInvalid() throws Exception { Visit Visit = new Visit(); - visitDAO.insertVisit(Visit); + visitDAO.insert(Visit); } @Test(expected = PersistenceException.class) public void shouldInsertVisitThrowExceptionWhenVisitIdIsNotDefault() throws Exception { Visit Visit = new Visit(); Visit.setId(123); - visitDAO.insertVisit(Visit); + visitDAO.insert(Visit); } @Test public void shouldDeleteVisitWhenVisitExists() throws Exception { - visitDAO.deleteVisit(1); + visitDAO.deleteById(1); } @Test(expected = EntityNotFoundException.class) public void shouldDeleteVisitThrowExceptionWhenVisitNotExists() throws Exception { - visitDAO.deleteVisit(123); + visitDAO.deleteById(123); } } diff --git a/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java b/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java index 5b60083..124f731 100644 --- a/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java @@ -122,7 +122,7 @@ public void shouldCreateOwnerAndShowOwnerDetail() throws Exception { .andExpect(redirectedUrl("/owners/123")); // The following verification passes if remove @WebMvc, so // this should be a bug in Spring Boot. - // verify(ownerRepository).insertOwner(any(Owner.class)); + // verify(ownerRepository).insert(any(Owner.class)); } @Test @@ -140,7 +140,7 @@ public void shouldFailToCreateOwnerWhenOwnerInformationIsIncomplete() throws Exc ; // The following verification passes if remove @WebMvc, so // this should be a bug in Spring Boot. - // verify(ownerRepository).insertOwner(any(Owner.class)); + // verify(ownerRepository).insert(any(Owner.class)); } @Test @@ -189,7 +189,7 @@ public void shouldFailToUpdateOwnerWhenOwnerIdIsInvalid() throws Exception { .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attribute("exception", exception)); -// verify(ownerRepository).updateOwner(any()); +// verify(ownerRepository).update(any()); } @Test diff --git a/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java index be2a725..659c875 100644 --- a/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java @@ -41,13 +41,13 @@ private List createOwnerListSample() { @Test public void shouldGetAllOwnersReturnListOfOwners() throws Exception { - when(ownerDAOMock.getAllOwners()).thenReturn(ownerListSample); + when(ownerDAOMock.getAll()).thenReturn(ownerListSample); assertEquals(ownerListSample, ownerRepository.getAllOwners()); } @Test public void shouldGetOwnerByIdReturnAnOwnerIfExists() throws Exception { - when(ownerDAOMock.getOwnerById(0)).thenReturn(ownerSample); + when(ownerDAOMock.getById(0)).thenReturn(ownerSample); assertEquals(ownerSample, ownerRepository.getOwnerById(0)); } } From c4fee970db00a2da866bc6958285d83f011af770 Mon Sep 17 00:00:00 2001 From: PunCha Date: Fri, 19 Aug 2016 23:50:33 +0800 Subject: [PATCH 05/29] Add unit test for All Repositories --- .../puncha/repositories/OwnerRepository.java | 4 +- .../tk/puncha/repositories/PetRepository.java | 1 - .../repositories/OwnerRepositoryTests.java | 85 ++++++++++++------ .../unit/repositories/PetRepositoryTests.java | 90 +++++++++++++++++++ .../repositories/PetTypeRepositoryTests.java | 45 ++++++++++ .../repositories/VisitRepositoryTests.java | 39 ++++++++ 6 files changed, 234 insertions(+), 30 deletions(-) create mode 100644 src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java create mode 100644 src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java create mode 100644 src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java diff --git a/src/main/java/tk/puncha/repositories/OwnerRepository.java b/src/main/java/tk/puncha/repositories/OwnerRepository.java index ac1f9f8..296f65c 100644 --- a/src/main/java/tk/puncha/repositories/OwnerRepository.java +++ b/src/main/java/tk/puncha/repositories/OwnerRepository.java @@ -38,8 +38,8 @@ public Owner getOwnerWithPetsById(int ownerId) { } @Transactional - public void insertOwner(Owner owner) { - ownerDAO.insert(owner); + public int insertOwner(Owner owner) { + return ownerDAO.insert(owner); } @Transactional diff --git a/src/main/java/tk/puncha/repositories/PetRepository.java b/src/main/java/tk/puncha/repositories/PetRepository.java index 6435fd9..1ff9d0e 100644 --- a/src/main/java/tk/puncha/repositories/PetRepository.java +++ b/src/main/java/tk/puncha/repositories/PetRepository.java @@ -29,7 +29,6 @@ public List getAllPets() { return petDAO.getAll(); } - @Transactional(readOnly = true) public Pet getPetById(int id) { return petDAO.getById(id); diff --git a/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java index 659c875..999a9b2 100644 --- a/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java @@ -1,53 +1,84 @@ package tk.puncha.unit.repositories; -import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import tk.puncha.dao.OwnerDAO; import tk.puncha.models.Owner; import tk.puncha.repositories.OwnerRepository; -import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.*; +@RunWith(MockitoJUnitRunner.class) public class OwnerRepositoryTests { - private OwnerRepository ownerRepository; + @Mock + private Owner ownerMock; + @Mock + private List ownerListMock; + @Mock private OwnerDAO ownerDAOMock; - private Owner ownerSample; - private List ownerListSample; - - @Before - public void before() { - ownerDAOMock = mock(OwnerDAO.class); - ownerRepository = new OwnerRepository(ownerDAOMock); - ownerSample = createOwnerSample(); - ownerListSample = createOwnerListSample(); + @InjectMocks + private OwnerRepository ownerRepository; + + @Test + public void shouldGetAllOwnersDispatchCallToDAO() throws Exception { + when(ownerDAOMock.getAll()).thenReturn(ownerListMock); + assertEquals(ownerListMock, ownerRepository.getAllOwners()); + verify(ownerDAOMock).getAll(); + verifyNoMoreInteractions(ownerDAOMock); + } + + @Test + public void shouldGetOwnerByIdDispatchCallToDAO() throws Exception { + when(ownerDAOMock.getById(anyInt())).thenReturn(ownerMock); + assertEquals(ownerMock, ownerRepository.getOwnerById(anyInt())); + verify(ownerDAOMock).getById(anyInt()); + verifyNoMoreInteractions(ownerDAOMock); + } + + @Test + public void shouldGetByIdWithPetsDispatchCallToDAO() throws Exception { + when(ownerDAOMock.getByIdWithPets(anyInt())).thenReturn(ownerMock); + assertEquals(ownerMock, ownerRepository.getOwnerWithPetsById(anyInt())); + verify(ownerDAOMock).getByIdWithPets(anyInt()); + verifyNoMoreInteractions(ownerDAOMock); } - private Owner createOwnerSample() { - Owner owner = new Owner(); - owner.setFirstName("puncha"); - owner.setLastName("feng"); - return owner; + @Test + public void shouldFindByFirstNameDispatchCallToDAO() throws Exception { + when(ownerDAOMock.findByFirstName(anyString())).thenReturn(ownerListMock); + assertEquals(ownerListMock, ownerRepository.getOwnersByFirstName(anyString())); + verify(ownerDAOMock).findByFirstName(anyString()); + verifyNoMoreInteractions(ownerDAOMock); } - private List createOwnerListSample() { - return Collections.singletonList(ownerSample); + @Test + public void shouldInsertDispatchCallToDAO() throws Exception { + when(ownerDAOMock.insert(any(Owner.class))).thenReturn(123); + assertEquals(123, ownerRepository.insertOwner(any(Owner.class))); + verify(ownerDAOMock).insert(any(Owner.class)); + verifyNoMoreInteractions(ownerDAOMock); } @Test - public void shouldGetAllOwnersReturnListOfOwners() throws Exception { - when(ownerDAOMock.getAll()).thenReturn(ownerListSample); - assertEquals(ownerListSample, ownerRepository.getAllOwners()); + public void shouldDeleteByIdDispatchCallToDAO() throws Exception { + doNothing().when(ownerDAOMock).deleteById(anyInt()); + ownerRepository.deleteOwner(anyInt()); + verify(ownerDAOMock).deleteById(anyInt()); + verifyNoMoreInteractions(ownerDAOMock); } @Test - public void shouldGetOwnerByIdReturnAnOwnerIfExists() throws Exception { - when(ownerDAOMock.getById(0)).thenReturn(ownerSample); - assertEquals(ownerSample, ownerRepository.getOwnerById(0)); + public void shouldUpdateDispatchCallToDAO() throws Exception { + doNothing().when(ownerDAOMock).update(any(Owner.class)); + ownerRepository.updateOwner(any(Owner.class)); + verify(ownerDAOMock).update(any(Owner.class)); } } diff --git a/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java new file mode 100644 index 0000000..ca858bd --- /dev/null +++ b/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java @@ -0,0 +1,90 @@ +package tk.puncha.unit.repositories; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import tk.puncha.dao.PetDAO; +import tk.puncha.dao.PetTypeDAO; +import tk.puncha.models.Pet; +import tk.puncha.models.PetType; +import tk.puncha.repositories.PetRepository; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.*; + +@RunWith(MockitoJUnitRunner.class) +public class PetRepositoryTests { + + @Mock + private Pet petMock; + @Mock + private List petListMock; + @Mock + private PetDAO petDAOMock; + @Mock + private PetTypeDAO petTypeDAOMock; + @Mock + private List petTypeListMock; + @InjectMocks + private PetRepository petRepository; + + @Test + public void shouldGetAllPetsDispatchCallToDAO() throws Exception { + when(petDAOMock.getAll()).thenReturn(petListMock); + assertEquals(petListMock, petRepository.getAllPets()); + verify(petDAOMock).getAll(); + verifyNoMoreInteractions(petDAOMock); + } + + @Test + public void shouldGetPetByIdDispatchCallToDAO() throws Exception { + when(petDAOMock.getById(anyInt())).thenReturn(petMock); + assertEquals(petMock, petRepository.getPetById(anyInt())); + verify(petDAOMock).getById(anyInt()); + verifyNoMoreInteractions(petDAOMock); + } + + @Test + public void shouldGetAllTypesDispatchCallToDAO() throws Exception { + when(petTypeDAOMock.getAll()).thenReturn(petTypeListMock); + assertEquals(petTypeListMock, petRepository.getAllTypes()); + verify(petTypeDAOMock).getAll(); + verifyNoMoreInteractions(petDAOMock, petTypeDAOMock); + } + + @Test + public void shouldInsertDispatchCallToDAO() throws Exception { + when(petDAOMock.insert(any(Pet.class))).thenReturn(123); + assertEquals(123, petRepository.insertPet(any(Pet.class))); + verify(petDAOMock).insert(any(Pet.class)); + verifyNoMoreInteractions(petDAOMock); + } + + @Test + public void shouldUpdateDispatchCallToDAO() throws Exception { + doNothing().when(petDAOMock).update(any(Pet.class)); + petRepository.updatePet(any(Pet.class)); + verify(petDAOMock).update(any(Pet.class)); + } + + @Test + public void shouldDeleteByIdDispatchCallToDAO() throws Exception { + doNothing().when(petDAOMock).deleteById(anyInt()); + petRepository.delete(anyInt()); + verify(petDAOMock).deleteById(anyInt()); + verifyNoMoreInteractions(petDAOMock); + } + + @Test + public void shouldDeleteByOwnerIdDispatchCallToDAO() throws Exception { + doNothing().when(petDAOMock).deleteByOwnerId(anyInt()); + petRepository.deletePetsByOwnerId(anyInt()); + verify(petDAOMock).deleteByOwnerId(anyInt()); + verifyNoMoreInteractions(petDAOMock); + } +} diff --git a/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java new file mode 100644 index 0000000..88f3ac0 --- /dev/null +++ b/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java @@ -0,0 +1,45 @@ +package tk.puncha.unit.repositories; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import tk.puncha.dao.PetTypeDAO; +import tk.puncha.models.PetType; +import tk.puncha.repositories.PetTypeRepository; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.*; + +@RunWith(MockitoJUnitRunner.class) +public class PetTypeRepositoryTests { + + @Mock + private PetType petTypeMock; + @Mock + private List petTypeListMock; + @Mock + private PetTypeDAO petTypeDAOMock; + @InjectMocks + private PetTypeRepository petTypeRepository; + + @Test + public void shouldGetAllPetTypesDispatchCallToDAO() throws Exception { + when(petTypeDAOMock.getAll()).thenReturn(petTypeListMock); + assertEquals(petTypeListMock, petTypeRepository.getAllTypes()); + verify(petTypeDAOMock).getAll(); + verifyNoMoreInteractions(petTypeDAOMock); + } + + @Test + public void shouldGetPetTypeByIdDispatchCallToDAO() throws Exception { + when(petTypeDAOMock.getById(anyInt())).thenReturn(petTypeMock); + assertEquals(petTypeMock, petTypeRepository.getPetTypeById(anyInt())); + verify(petTypeDAOMock).getById(anyInt()); + verifyNoMoreInteractions(petTypeDAOMock); + } +} diff --git a/src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java new file mode 100644 index 0000000..08a208e --- /dev/null +++ b/src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java @@ -0,0 +1,39 @@ +package tk.puncha.unit.repositories; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import tk.puncha.dao.VisitDAO; +import tk.puncha.models.Visit; +import tk.puncha.repositories.VisitRepository; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.*; + +@RunWith(MockitoJUnitRunner.class) +public class VisitRepositoryTests { + + @Mock + private VisitDAO visitDAOMock; + @InjectMocks + private VisitRepository visitRepository; + + @Test + public void shouldInsertDispatchCallToDAO() throws Exception { + when(visitDAOMock.insert(any(Visit.class))).thenReturn(123); + assertEquals(123, visitRepository.insertVisit(any(Visit.class))); + verify(visitDAOMock).insert(any(Visit.class)); + verifyNoMoreInteractions(visitDAOMock); + } + + @Test + public void shouldDeleteByIdDispatchCallToDAO() throws Exception { + doNothing().when(visitDAOMock).deleteById(anyInt()); + visitRepository.delete(anyInt()); + verify(visitDAOMock).deleteById(anyInt()); + verifyNoMoreInteractions(visitDAOMock); + } +} From d4c09b478ea8ecf4cd90c700bf788ac567b1c514 Mon Sep 17 00:00:00 2001 From: PunCha Date: Sat, 20 Aug 2016 00:04:37 +0800 Subject: [PATCH 06/29] Unify Repository method naming convention: getAll, getById, insert, update, deleteById... --- .../puncha/controllers/OwnerController.java | 14 ++++----- .../tk/puncha/controllers/PetController.java | 19 +++++++----- .../puncha/controllers/VisitController.java | 6 ++-- .../tk/puncha/formatters/OwnerFormatter.java | 2 +- .../puncha/formatters/PetTypeFormatter.java | 2 +- .../puncha/repositories/OwnerRepository.java | 25 ++++++++-------- .../tk/puncha/repositories/PetRepository.java | 16 ++++------ .../repositories/PetTypeRepository.java | 4 ++- .../puncha/repositories/VisitRepository.java | 11 ++++--- .../RestfulOwnerController.java | 12 ++++---- .../RestfulPetController.java | 8 ++--- .../RestfulVisitController.java | 6 ++-- .../repositories/OwnerRepositoryTests.java | 20 ++++++------- .../controllers/OwnerControllerTests.java | 30 +++++++++---------- .../unit/controllers/PetControllerTests.java | 18 +++++------ .../controllers/VisitControllerTests.java | 20 ++++++------- .../repositories/OwnerRepositoryTests.java | 18 +++++------ .../unit/repositories/PetRepositoryTests.java | 22 +++++--------- .../repositories/PetTypeRepositoryTests.java | 6 ++-- .../repositories/VisitRepositoryTests.java | 4 +-- 20 files changed, 126 insertions(+), 137 deletions(-) diff --git a/src/main/java/tk/puncha/controllers/OwnerController.java b/src/main/java/tk/puncha/controllers/OwnerController.java index 68d71e2..921e1bd 100644 --- a/src/main/java/tk/puncha/controllers/OwnerController.java +++ b/src/main/java/tk/puncha/controllers/OwnerController.java @@ -39,9 +39,9 @@ public void dataBinding(WebDataBinder binder) { public ModelAndView index(@RequestParam(name = "search-first-name", required = false) String firstNameToSearch) { List owners; if (firstNameToSearch == null || firstNameToSearch.isEmpty()) - owners = ownerRepository.getAllOwners(); + owners = ownerRepository.getAll(); else - owners = ownerRepository.getOwnersByFirstName(firstNameToSearch); + owners = ownerRepository.findByFirstName(firstNameToSearch); ModelAndView modelView = new ModelAndView(); modelView.addObject("owners", owners); @@ -52,7 +52,7 @@ public ModelAndView index(@RequestParam(name = "search-first-name", required = f @GetMapping("{ownerId}") public ModelAndView view(@PathVariable int ownerId) { - Owner owner = ownerRepository.getOwnerWithPetsById(ownerId); + Owner owner = ownerRepository.getByIdWithPets(ownerId); ensureExist(owner); return createFormModelView("owner/viewOrEdit", owner, FormMode.Readonly); } @@ -70,22 +70,22 @@ public String createOrUpdate(@Valid Owner owner, BindingResult bindingResult, Mo } if (owner.getId() == -1) - ownerRepository.insertOwner(owner); + ownerRepository.insert(owner); else - ownerRepository.updateOwner(owner); + ownerRepository.update(owner); return "redirect:/owners/" + owner.getId(); } @GetMapping("{ownerId}/edit") public ModelAndView editOwner(@PathVariable int ownerId) { - Owner owner = ownerRepository.getOwnerById(ownerId); + Owner owner = ownerRepository.getById(ownerId); ensureExist(owner); return createFormModelView("owner/viewOrEdit", owner, FormMode.Edit); } @GetMapping("{ownerId}/delete") public String delete(@PathVariable int ownerId) { - ownerRepository.deleteOwner(ownerId); + ownerRepository.deleteById(ownerId); return "redirect:/owners"; } diff --git a/src/main/java/tk/puncha/controllers/PetController.java b/src/main/java/tk/puncha/controllers/PetController.java index 4a840cd..deebe15 100644 --- a/src/main/java/tk/puncha/controllers/PetController.java +++ b/src/main/java/tk/puncha/controllers/PetController.java @@ -20,6 +20,7 @@ import tk.puncha.models.PetType; import tk.puncha.repositories.OwnerRepository; import tk.puncha.repositories.PetRepository; +import tk.puncha.repositories.PetTypeRepository; import tk.puncha.views.json.view.PetJsonView; import javax.servlet.http.HttpSession; @@ -34,15 +35,17 @@ public class PetController extends ControllerBase { private static final Logger logger = LoggerFactory.getLogger(PetController.class); private final PetRepository petRepository; + private final PetTypeRepository petTypeRepository; private final OwnerRepository ownerRepository; private final OwnerFormatter ownerFormatter; private final PetTypeFormatter petTypeFormatter; @Autowired - public PetController(OwnerRepository ownerRepository, PetRepository petRepository, OwnerFormatter ownerFormatter, PetTypeFormatter petTypeFormatter) { + public PetController(OwnerRepository ownerRepository, PetRepository petRepository, PetTypeRepository petTypeRepository, OwnerFormatter ownerFormatter, PetTypeFormatter petTypeFormatter) { this.ownerRepository = ownerRepository; this.petRepository = petRepository; + this.petTypeRepository = petTypeRepository; this.ownerFormatter = ownerFormatter; this.petTypeFormatter = petTypeFormatter; } @@ -57,13 +60,13 @@ void initPetBinder(WebDataBinder binder) { @ModelAttribute("types") List getPetTypes() { logger.debug("getPetTypes()"); - return petRepository.getAllTypes(); + return petTypeRepository.getAllTypes(); } @ModelAttribute("owners") List getOwners() { logger.debug("getOwners()"); - return ownerRepository.getAllOwners(); + return ownerRepository.getAll(); } @GetMapping(value = {"", "/index", "/default"}, produces = MediaType.TEXT_HTML_VALUE) @@ -76,7 +79,7 @@ public ModelAndView htmlIndex() { @GetMapping("{id}") public ModelAndView view(@PathVariable int id) { logger.debug("view()"); - Pet pet = petRepository.getPetById(id); + Pet pet = petRepository.getById(id); ensureExist(pet); return createFormModelView(pet, FormMode.Readonly); } @@ -84,7 +87,7 @@ public ModelAndView view(@PathVariable int id) { @GetMapping("{id}/edit") public ModelAndView edit(@PathVariable int id, HttpSession httpSession) { logger.debug("edit()"); - Pet pet = petRepository.getPetById(id); + Pet pet = petRepository.getById(id); ensureExist(pet); httpSession.setAttribute("id", pet.getId()); return createFormModelView(pet, FormMode.Edit); @@ -112,9 +115,9 @@ public String processPetCreationForm( } if (petId != -1) { pet.setId(petId); - petRepository.updatePet(pet); + petRepository.update(pet); } else { - petId = petRepository.insertPet(pet); + petId = petRepository.insert(pet); } sessionStatus.setComplete(); return "redirect:/pets/" + petId; @@ -123,7 +126,7 @@ public String processPetCreationForm( @GetMapping("{id}/delete") public String delete(@PathVariable int id) { logger.debug("delete()"); - petRepository.delete(id); + petRepository.deleteById(id); return "redirect:/pets"; } diff --git a/src/main/java/tk/puncha/controllers/VisitController.java b/src/main/java/tk/puncha/controllers/VisitController.java index 67c8c2c..6e2c8e9 100644 --- a/src/main/java/tk/puncha/controllers/VisitController.java +++ b/src/main/java/tk/puncha/controllers/VisitController.java @@ -33,13 +33,13 @@ public VisitController(PetRepository petRepository, VisitRepository visitReposit @ModelAttribute("pet") Pet getPetById(@PathVariable int petId) { - return petRepository.getPetById(petId); + return petRepository.getById(petId); } @RequestMapping("{visitId}/delete") public String deleteVisit(@ModelAttribute Pet pet, @PathVariable int visitId) { if (pet == null) throw new RuntimeException("Pet doesn't exist!"); - visitRepository.delete(visitId); + visitRepository.deleteById(visitId); return "redirect:/pets/{petId}"; } @@ -56,7 +56,7 @@ public String processCreationForm(Pet pet, @ModelAttribute @Valid Visit visit, B pet.getVisits().add(visit); visit.setPet(pet); - petRepository.updatePet(pet); + petRepository.update(pet); return "redirect:/pets/{petId}"; } } diff --git a/src/main/java/tk/puncha/formatters/OwnerFormatter.java b/src/main/java/tk/puncha/formatters/OwnerFormatter.java index 42fc693..875ca79 100644 --- a/src/main/java/tk/puncha/formatters/OwnerFormatter.java +++ b/src/main/java/tk/puncha/formatters/OwnerFormatter.java @@ -21,7 +21,7 @@ public OwnerFormatter(OwnerRepository ownerRepository) { @Override public Owner parse(String text, Locale locale) throws ParseException { - return ownerRepository.getOwnerById(Integer.parseInt(text)); + return ownerRepository.getById(Integer.parseInt(text)); } @Override diff --git a/src/main/java/tk/puncha/formatters/PetTypeFormatter.java b/src/main/java/tk/puncha/formatters/PetTypeFormatter.java index 5ff1f5d..a1f150f 100644 --- a/src/main/java/tk/puncha/formatters/PetTypeFormatter.java +++ b/src/main/java/tk/puncha/formatters/PetTypeFormatter.java @@ -17,7 +17,7 @@ public class PetTypeFormatter implements Formatter { @Override public PetType parse(String text, Locale locale) throws ParseException { - return petTypeRepository.getPetTypeById(Integer.parseInt(text, 10)); + return petTypeRepository.getById(Integer.parseInt(text, 10)); } @Override diff --git a/src/main/java/tk/puncha/repositories/OwnerRepository.java b/src/main/java/tk/puncha/repositories/OwnerRepository.java index 296f65c..505d9ea 100644 --- a/src/main/java/tk/puncha/repositories/OwnerRepository.java +++ b/src/main/java/tk/puncha/repositories/OwnerRepository.java @@ -9,6 +9,7 @@ import java.util.List; @Repository +@Transactional public class OwnerRepository { private final OwnerDAO ownerDAO; @@ -18,37 +19,35 @@ public OwnerRepository(OwnerDAO ownerDAO) { this.ownerDAO = ownerDAO; } - @Transactional - public List getAllOwners() { + @Transactional(readOnly = true) + public List getAll() { return ownerDAO.getAll(); } - public List getOwnersByFirstName(String firstName){ + @Transactional(readOnly = true) + public List findByFirstName(String firstName){ return ownerDAO.findByFirstName(firstName); } - @Transactional - public Owner getOwnerById(int ownerId) { + @Transactional(readOnly = true) + public Owner getById(int ownerId) { return ownerDAO.getById(ownerId); } - @Transactional - public Owner getOwnerWithPetsById(int ownerId) { + @Transactional(readOnly = true) + public Owner getByIdWithPets(int ownerId) { return ownerDAO.getByIdWithPets(ownerId); } - @Transactional - public int insertOwner(Owner owner) { + public int insert(Owner owner) { return ownerDAO.insert(owner); } - @Transactional - public void updateOwner(Owner owner) { + public void update(Owner owner) { ownerDAO.update(owner); } - @Transactional - public void deleteOwner(int ownerId) { + public void deleteById(int ownerId) { ownerDAO.deleteById(ownerId); } } diff --git a/src/main/java/tk/puncha/repositories/PetRepository.java b/src/main/java/tk/puncha/repositories/PetRepository.java index 1ff9d0e..da813ba 100644 --- a/src/main/java/tk/puncha/repositories/PetRepository.java +++ b/src/main/java/tk/puncha/repositories/PetRepository.java @@ -6,7 +6,6 @@ import tk.puncha.dao.PetDAO; import tk.puncha.dao.PetTypeDAO; import tk.puncha.models.Pet; -import tk.puncha.models.PetType; import java.util.List; @@ -30,28 +29,23 @@ public List getAllPets() { } @Transactional(readOnly = true) - public Pet getPetById(int id) { + public Pet getById(int id) { return petDAO.getById(id); } - public void updatePet(Pet pet) { + public void update(Pet pet) { petDAO.update(pet); } - public int insertPet(Pet pet) { + public int insert(Pet pet) { return petDAO.insert(pet); } - public void delete(int id) { + public void deleteById(int id) { petDAO.deleteById(id); } - @Transactional(readOnly = true) - public List getAllTypes() { - return petTypeDAO.getAll(); - } - - public void deletePetsByOwnerId(int ownerId) { + public void deleteByOwnerId(int ownerId) { petDAO.deleteByOwnerId(ownerId); } } diff --git a/src/main/java/tk/puncha/repositories/PetTypeRepository.java b/src/main/java/tk/puncha/repositories/PetTypeRepository.java index 5651cd0..30f0d3d 100644 --- a/src/main/java/tk/puncha/repositories/PetTypeRepository.java +++ b/src/main/java/tk/puncha/repositories/PetTypeRepository.java @@ -2,12 +2,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; import tk.puncha.dao.PetTypeDAO; import tk.puncha.models.PetType; import java.util.List; @Repository +@Transactional(readOnly = true) public class PetTypeRepository { private final PetTypeDAO petTypeDAO; @@ -21,7 +23,7 @@ public List getAllTypes() { return petTypeDAO.getAll(); } - public PetType getPetTypeById(int id) { + public PetType getById(int id) { return petTypeDAO.getById(id); } } diff --git a/src/main/java/tk/puncha/repositories/VisitRepository.java b/src/main/java/tk/puncha/repositories/VisitRepository.java index 01e0d3c..6e7b403 100644 --- a/src/main/java/tk/puncha/repositories/VisitRepository.java +++ b/src/main/java/tk/puncha/repositories/VisitRepository.java @@ -1,12 +1,13 @@ package tk.puncha.repositories; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import tk.puncha.dao.VisitDAO; import tk.puncha.models.Visit; -@Component +@Repository +@Transactional public class VisitRepository { private final VisitDAO visitDAO; @@ -16,13 +17,11 @@ public VisitRepository(VisitDAO visitDAO) { this.visitDAO = visitDAO; } - @Transactional - public int insertVisit(Visit visit) { + public int insert(Visit visit) { return visitDAO.insert(visit); } - @Transactional - public void delete(int id) { + public void deleteById(int id) { visitDAO.deleteById(id); } } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java b/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java index 0a99750..d521100 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java @@ -47,20 +47,20 @@ public void dataBinding(WebDataBinder binder) { @JsonView(OwnerJsonView.Default.class) public List getAllOwners(@RequestParam(required = false) String firstName) { if (firstName != null && !firstName.isEmpty()) - return ownerRepository.getOwnersByFirstName(firstName); + return ownerRepository.findByFirstName(firstName); else - return ownerRepository.getAllOwners(); + return ownerRepository.getAll(); } @GetMapping("{ownerId}") @JsonView(OwnerJsonView.WithPets.class) public Owner getOwner(@PathVariable int ownerId) { - return ownerRepository.getOwnerWithPetsById(ownerId); + return ownerRepository.getByIdWithPets(ownerId); } @DeleteMapping("{ownerId}") public void deleteOwner(@PathVariable int ownerId) { - ownerRepository.deleteOwner(ownerId); + ownerRepository.deleteById(ownerId); } @PostMapping @@ -70,7 +70,7 @@ public ResponseEntity createOwner(@Valid @RequestBody Owner owner, BindingResult String.format("Field: %s is invalid.", error.getFieldError().getField())); return ResponseEntity.badRequest().body(errorInfo); } - ownerRepository.insertOwner(owner); + ownerRepository.insert(owner); return ResponseEntity.ok(owner); } @@ -83,7 +83,7 @@ public ResponseEntity updateOwner(@Valid @RequestBody Owner owner, BindingResult } // clear the pet collection to avoid updating pets owner.getPets().clear(); - ownerRepository.updateOwner(owner); + ownerRepository.update(owner); return ResponseEntity.noContent().build(); } } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java b/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java index c869acd..762c28e 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java @@ -39,7 +39,7 @@ public List query() { @GetMapping("{id}") @JsonView(PetJsonView.class) public Pet get(@PathVariable int id) { - return petRepository.getPetById(id); + return petRepository.getById(id); } @PostMapping @@ -47,7 +47,7 @@ public void create(@Valid @RequestBody Pet pet, BindingResult bindingResult) { if (bindingResult.hasErrors()) { throw new RuntimeException("Invalid data."); } - petRepository.insertPet(pet); + petRepository.insert(pet); } @PostMapping("{id}") @@ -55,11 +55,11 @@ public void update(@Valid @RequestBody Pet pet, BindingResult bindingResult) { if (bindingResult.hasErrors()) { throw new RuntimeException("Invalid data."); } - petRepository.updatePet(pet); + petRepository.update(pet); } @DeleteMapping("{id}") public void delete(@PathVariable int id) { - petRepository.delete(id); + petRepository.deleteById(id); } } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java b/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java index 82f8c4b..4a1faed 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java @@ -32,17 +32,17 @@ public ErrorInfo handleException(Exception exception) { @ModelAttribute("pet") public Pet getPet(@PathVariable int petId) { - return petRepository.getPetById(petId); + return petRepository.getById(petId); } @PostMapping public void create(Pet pet, @Valid @RequestBody Visit visit) { visit.setPet(pet); - visitRepository.insertVisit(visit); + visitRepository.insert(visit); } @DeleteMapping("{id}") public void delete(@PathVariable int id) { - visitRepository.delete(id); + visitRepository.deleteById(id); } } diff --git a/src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java b/src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java index 5231ae2..c4cb56f 100644 --- a/src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java +++ b/src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java @@ -34,13 +34,13 @@ static class Dummy extends Application { @Test public void shouldGetAllOwnersReturnListOfOwners() throws Exception { - List allOwners = ownerRepository.getAllOwners(); + List allOwners = ownerRepository.getAll(); assertEquals(10, allOwners.size()); } @Test public void shouldGetOwnerByIdReturnAnOwnerIfExists() throws Exception { - Owner owner = ownerRepository.getOwnerById(1); + Owner owner = ownerRepository.getById(1); assertEquals(1, owner.getId()); assertEquals("George", owner.getFirstName()); assertEquals("Franklin", owner.getLastName()); @@ -52,13 +52,13 @@ public void shouldGetOwnerByIdReturnAnOwnerIfExists() throws Exception { @Test public void shouldGetOwnerByIdReturnNullIfOwnerNotExists() throws Exception { - Owner owner = ownerRepository.getOwnerById(-1); + Owner owner = ownerRepository.getById(-1); assertNull(owner); } @Test public void shouldGetOwnerWithPetsByIdReturnInitializedPetsCollection() throws Exception { - Owner owner = ownerRepository.getOwnerWithPetsById(1); + Owner owner = ownerRepository.getByIdWithPets(1); assertEquals(1, owner.getId()); assertTrue(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); } @@ -68,21 +68,21 @@ public void shouldInsertOwner() throws Exception { Owner owner = new Owner(); owner.setFirstName("puncha"); owner.setLastName("feng"); - ownerRepository.insertOwner(owner); - assertNotNull(ownerRepository.getOwnerById(owner.getId())); + ownerRepository.insert(owner); + assertNotNull(ownerRepository.getById(owner.getId())); } @Test(expected = ConstraintViolationException.class) public void shouldInsertOwnerThrowIfOwnerIsInvalid() throws Exception { Owner owner = new Owner(); - ownerRepository.insertOwner(owner); + ownerRepository.insert(owner); } @Test public void shouldUpdateOwner() throws Exception { - Owner owner = ownerRepository.getOwnerById(2); + Owner owner = ownerRepository.getById(2); owner.setFirstName("puncha"); - ownerRepository.updateOwner(owner); - assertEquals("puncha", ownerRepository.getOwnerById(2).getFirstName()); + ownerRepository.update(owner); + assertEquals("puncha", ownerRepository.getById(2).getFirstName()); } } diff --git a/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java b/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java index 124f731..64d65a8 100644 --- a/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java @@ -42,32 +42,32 @@ public class OwnerControllerTests { @Test public void shouldShowAllOwners() throws Exception { List owners = new ArrayList<>(); - when(ownerRepository.getAllOwners()).thenReturn(owners); + when(ownerRepository.getAll()).thenReturn(owners); mockMvc.perform(get("/owners")) .andExpect(status().isOk()) .andExpect(view().name("owner/index")) .andExpect(model().attributeExists("owners")); - verify(ownerRepository).getAllOwners(); + verify(ownerRepository).getAll(); } @Test public void shouldShowOwnersMatchedByFirstName() throws Exception { List owners = new ArrayList<>(); - when(ownerRepository.getOwnersByFirstName(anyString())).thenReturn(owners); + when(ownerRepository.findByFirstName(anyString())).thenReturn(owners); // search for George mockMvc.perform(get("/owners").param("search-first-name", "gEora")) .andExpect(status().isOk()) .andExpect(view().name("owner/index")) .andExpect(model().attributeExists("owners")); - verify(ownerRepository).getOwnersByFirstName("gEora"); + verify(ownerRepository).findByFirstName("gEora"); } @Test public void shouldShowOwnerDetail() throws Exception { Owner owner = mock(Owner.class); - when(ownerRepository.getOwnerWithPetsById(1)).thenReturn(owner); + when(ownerRepository.getByIdWithPets(1)).thenReturn(owner); when(ownerValidator.supports(owner.getClass())).thenReturn(true); mockMvc.perform(get("/owners/1")) @@ -76,21 +76,21 @@ public void shouldShowOwnerDetail() throws Exception { .andExpect(model().attribute("owner", owner)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Readonly)); - verify(ownerRepository).getOwnerWithPetsById(1); + verify(ownerRepository).getByIdWithPets(1); // validator is called even if we return the model verify(ownerValidator).supports(owner.getClass()); } @Test public void shouldFailToShowOwnerDetailWhenOwnerDoesNotExist() throws Exception { - when(ownerRepository.getOwnerWithPetsById(anyInt())).thenReturn(null); + when(ownerRepository.getByIdWithPets(anyInt())).thenReturn(null); mockMvc.perform(get("/owners/100")) .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attributeExists("exception")); - verify(ownerRepository).getOwnerWithPetsById(100); + verify(ownerRepository).getByIdWithPets(100); } @Test @@ -110,7 +110,7 @@ public void shouldCreateOwnerAndShowOwnerDetail() throws Exception { Owner owner = invocation.getArgumentAt(0, Owner.class); owner.setId(123); return null; - }).when(ownerRepository).insertOwner(any(Owner.class)); + }).when(ownerRepository).insert(any(Owner.class)); MockHttpServletRequestBuilder req = post("/owners/new") .param("firstName", "PunCha") .param("lastName", "Feng") @@ -146,7 +146,7 @@ public void shouldFailToCreateOwnerWhenOwnerInformationIsIncomplete() throws Exc @Test public void shouldShowOwnerEditForm() throws Exception { Owner owner = mock(Owner.class); - when(ownerRepository.getOwnerById(1)).thenReturn(owner); + when(ownerRepository.getById(1)).thenReturn(owner); when(ownerValidator.supports(owner.getClass())).thenReturn(true); mockMvc.perform(get("/owners/1/edit")) @@ -155,7 +155,7 @@ public void shouldShowOwnerEditForm() throws Exception { .andExpect(model().attribute("owner", owner)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Edit)); - verify(ownerRepository).getOwnerById(1); + verify(ownerRepository).getById(1); // validator is called even if we return the model verify(ownerValidator).supports(owner.getClass()); } @@ -178,7 +178,7 @@ public void shouldUpdateOwnerAnsShowOwnerDetail() throws Exception { @Test public void shouldFailToUpdateOwnerWhenOwnerIdIsInvalid() throws Exception { RuntimeException exception = new RuntimeException(); - doThrow(exception).when(ownerRepository).updateOwner(any()); + doThrow(exception).when(ownerRepository).update(any()); when(ownerValidator.supports(any())).thenReturn(true); MockHttpServletRequestBuilder req = post("/owners/new") @@ -197,17 +197,17 @@ public void shouldDeleteOwnerAndShowAllOwners() throws Exception { mockMvc.perform(get("/owners/1/delete")) .andExpect(status().is(302)) .andExpect(redirectedUrl("/owners")); - verify(ownerRepository).deleteOwner(1); + verify(ownerRepository).deleteById(1); } @Test public void shouldFailToDeleteOwnerWhenOwnerDoesNotExist() throws Exception { RuntimeException exception = new RuntimeException(); - doThrow(exception).when(ownerRepository).deleteOwner(100); + doThrow(exception).when(ownerRepository).deleteById(100); mockMvc.perform(get("/owners/100/delete")) .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attribute("exception", exception)); - verify(ownerRepository).deleteOwner(100); + verify(ownerRepository).deleteById(100); } } diff --git a/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java b/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java index 11b0e88..03047da 100644 --- a/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java @@ -63,7 +63,7 @@ public void shouldShowAllPets() throws Exception { @Test public void shouldShowPetDetail() throws Exception { Pet pet = mock(Pet.class); - when(petRepository.getPetById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(pet); mockMvc.perform(get("/pets/1")) .andExpect(status().isOk()) @@ -73,19 +73,19 @@ public void shouldShowPetDetail() throws Exception { .andExpect(model().attribute("pet", pet)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Readonly)); - verify(petRepository).getPetById(1); + verify(petRepository).getById(1); } @Test public void shouldFailToShowPetDetailWhenPetDoesNotExist() throws Exception { - when(petRepository.getPetById(anyInt())).thenReturn(null); + when(petRepository.getById(anyInt())).thenReturn(null); mockMvc.perform(get("/pets/100")) .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attributeExists("exception")); - verify(petRepository).getPetById(100); + verify(petRepository).getById(100); } @Test @@ -101,7 +101,7 @@ public void shouldShowPetCreationForm() throws Exception { @Test public void shouldCreatePet() throws Exception { - when(petRepository.insertPet(any())).thenReturn(123); + when(petRepository.insert(any())).thenReturn(123); when(petTypeFormatter.parse(any(), any())).thenReturn(mock(PetType.class)); when(ownerFormatter.parse(any(), any())).thenReturn(mock(Owner.class)); MockHttpServletRequestBuilder req = post("/pets/new") @@ -117,7 +117,7 @@ public void shouldCreatePet() throws Exception { @Test public void shouldFailToCreatePetWhenPetInformationIsIncomplete() throws Exception { - when(petRepository.insertPet(any())).thenReturn(123); + when(petRepository.insert(any())).thenReturn(123); MockHttpServletRequestBuilder req = post("/pets/new") .sessionAttr("id", "-1") .param("name", "puncha"); @@ -136,7 +136,7 @@ public void shouldFailToCreatePetWhenPetInformationIsIncomplete() throws Excepti @Test public void shouldShowPetEditForm() throws Exception { Pet pet = mock(Pet.class); - when(petRepository.getPetById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(pet); mockMvc.perform(get("/pets/1/edit")) .andExpect(status().isOk()) @@ -146,7 +146,7 @@ public void shouldShowPetEditForm() throws Exception { .andExpect(model().attribute("pet", pet)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Edit)); - verify(petRepository).getPetById(1); + verify(petRepository).getById(1); } @Test @@ -173,7 +173,7 @@ public void shouldDeletePetAndShowAllPets() throws Exception { @Test public void shouldFailToDeletePetWhenPetDoesNotExist() throws Exception { RuntimeException exception = new RuntimeException(); - doThrow(exception).when(petRepository).delete(100); + doThrow(exception).when(petRepository).deleteById(100); mockMvc.perform(get("/pets/100/delete")) .andExpect(status().isOk()) .andExpect(view().name("exception/default")) diff --git a/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java b/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java index cdbd749..25dcaf4 100644 --- a/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java @@ -37,7 +37,7 @@ public class VisitControllerTests { @Test public void shouldShowVisitCreationForm() throws Exception { Pet pet = mock(Pet.class); - when(petRepository.getPetById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(pet); mockMvc.perform(get("/pets/1/visits/new")) .andExpect(status().isOk()) .andExpect(view().name("visit/new")) @@ -48,7 +48,7 @@ public void shouldShowVisitCreationForm() throws Exception { @Test public void shouldCreateVisitAndShowPetDetail() throws Exception { Pet pet = mock(Pet.class); - when(petRepository.getPetById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(pet); MockHttpServletRequestBuilder req = post("/pets/1/visits/new") .param("description", "...") .param("visitDate", "1999-09-09"); @@ -60,7 +60,7 @@ public void shouldCreateVisitAndShowPetDetail() throws Exception { @Test public void shouldFailToCreateVisitWhenVisitInformationIsIncomplete() throws Exception { Pet pet = mock(Pet.class); - when(petRepository.getPetById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(pet); mockMvc.perform(post("/pets/1/visits/new")) .andExpect(status().isOk()) .andExpect(view().name("visit/new")) @@ -71,33 +71,33 @@ public void shouldFailToCreateVisitWhenVisitInformationIsIncomplete() throws Exc @Test public void shouldDeleteVisitAndShowPetDetail() throws Exception { - when(petRepository.getPetById(1)).thenReturn(mock(Pet.class)); + when(petRepository.getById(1)).thenReturn(mock(Pet.class)); mockMvc.perform(get("/pets/1/visits/2/delete")) .andExpect(status().is(302)) .andExpect(redirectedUrl("/pets/1")); - verify(visitRepository).delete(2); + verify(visitRepository).deleteById(2); } @Test public void shouldFailToDeleteVisitWhenVisitDoesNotExist() throws Exception { - when(petRepository.getPetById(1)).thenReturn(mock(Pet.class)); + when(petRepository.getById(1)).thenReturn(mock(Pet.class)); RuntimeException exception = new RuntimeException(); - doThrow(exception).when(visitRepository).delete(2); + doThrow(exception).when(visitRepository).deleteById(2); mockMvc.perform(get("/pets/1/visits/2/delete")) .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attribute("exception", exception)); - verify(visitRepository).delete(2); + verify(visitRepository).deleteById(2); } @Test public void shouldFailToDeleteVisitWhenPetDoesNotExist() throws Exception { - when(petRepository.getPetById(anyInt())).thenReturn(null); + when(petRepository.getById(anyInt())).thenReturn(null); mockMvc.perform(get("/pets/1/visits/2/delete")) .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attributeExists("exception")); - verify(petRepository).getPetById(1); + verify(petRepository).getById(1); } @Test diff --git a/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java index 999a9b2..7567c79 100644 --- a/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/OwnerRepositoryTests.java @@ -28,17 +28,17 @@ public class OwnerRepositoryTests { private OwnerRepository ownerRepository; @Test - public void shouldGetAllOwnersDispatchCallToDAO() throws Exception { + public void shouldGetAllDispatchCallToDAO() throws Exception { when(ownerDAOMock.getAll()).thenReturn(ownerListMock); - assertEquals(ownerListMock, ownerRepository.getAllOwners()); + assertEquals(ownerListMock, ownerRepository.getAll()); verify(ownerDAOMock).getAll(); verifyNoMoreInteractions(ownerDAOMock); } @Test - public void shouldGetOwnerByIdDispatchCallToDAO() throws Exception { + public void shouldGetByIdDispatchCallToDAO() throws Exception { when(ownerDAOMock.getById(anyInt())).thenReturn(ownerMock); - assertEquals(ownerMock, ownerRepository.getOwnerById(anyInt())); + assertEquals(ownerMock, ownerRepository.getById(anyInt())); verify(ownerDAOMock).getById(anyInt()); verifyNoMoreInteractions(ownerDAOMock); } @@ -46,7 +46,7 @@ public void shouldGetOwnerByIdDispatchCallToDAO() throws Exception { @Test public void shouldGetByIdWithPetsDispatchCallToDAO() throws Exception { when(ownerDAOMock.getByIdWithPets(anyInt())).thenReturn(ownerMock); - assertEquals(ownerMock, ownerRepository.getOwnerWithPetsById(anyInt())); + assertEquals(ownerMock, ownerRepository.getByIdWithPets(anyInt())); verify(ownerDAOMock).getByIdWithPets(anyInt()); verifyNoMoreInteractions(ownerDAOMock); } @@ -54,7 +54,7 @@ public void shouldGetByIdWithPetsDispatchCallToDAO() throws Exception { @Test public void shouldFindByFirstNameDispatchCallToDAO() throws Exception { when(ownerDAOMock.findByFirstName(anyString())).thenReturn(ownerListMock); - assertEquals(ownerListMock, ownerRepository.getOwnersByFirstName(anyString())); + assertEquals(ownerListMock, ownerRepository.findByFirstName(anyString())); verify(ownerDAOMock).findByFirstName(anyString()); verifyNoMoreInteractions(ownerDAOMock); } @@ -62,7 +62,7 @@ public void shouldFindByFirstNameDispatchCallToDAO() throws Exception { @Test public void shouldInsertDispatchCallToDAO() throws Exception { when(ownerDAOMock.insert(any(Owner.class))).thenReturn(123); - assertEquals(123, ownerRepository.insertOwner(any(Owner.class))); + assertEquals(123, ownerRepository.insert(any(Owner.class))); verify(ownerDAOMock).insert(any(Owner.class)); verifyNoMoreInteractions(ownerDAOMock); } @@ -70,7 +70,7 @@ public void shouldInsertDispatchCallToDAO() throws Exception { @Test public void shouldDeleteByIdDispatchCallToDAO() throws Exception { doNothing().when(ownerDAOMock).deleteById(anyInt()); - ownerRepository.deleteOwner(anyInt()); + ownerRepository.deleteById(anyInt()); verify(ownerDAOMock).deleteById(anyInt()); verifyNoMoreInteractions(ownerDAOMock); } @@ -78,7 +78,7 @@ public void shouldDeleteByIdDispatchCallToDAO() throws Exception { @Test public void shouldUpdateDispatchCallToDAO() throws Exception { doNothing().when(ownerDAOMock).update(any(Owner.class)); - ownerRepository.updateOwner(any(Owner.class)); + ownerRepository.update(any(Owner.class)); verify(ownerDAOMock).update(any(Owner.class)); } } diff --git a/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java index ca858bd..35064c3 100644 --- a/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java @@ -34,7 +34,7 @@ public class PetRepositoryTests { private PetRepository petRepository; @Test - public void shouldGetAllPetsDispatchCallToDAO() throws Exception { + public void shouldGetAllDispatchCallToDAO() throws Exception { when(petDAOMock.getAll()).thenReturn(petListMock); assertEquals(petListMock, petRepository.getAllPets()); verify(petDAOMock).getAll(); @@ -42,25 +42,17 @@ public void shouldGetAllPetsDispatchCallToDAO() throws Exception { } @Test - public void shouldGetPetByIdDispatchCallToDAO() throws Exception { + public void shouldGetByIdDispatchCallToDAO() throws Exception { when(petDAOMock.getById(anyInt())).thenReturn(petMock); - assertEquals(petMock, petRepository.getPetById(anyInt())); + assertEquals(petMock, petRepository.getById(anyInt())); verify(petDAOMock).getById(anyInt()); verifyNoMoreInteractions(petDAOMock); } - @Test - public void shouldGetAllTypesDispatchCallToDAO() throws Exception { - when(petTypeDAOMock.getAll()).thenReturn(petTypeListMock); - assertEquals(petTypeListMock, petRepository.getAllTypes()); - verify(petTypeDAOMock).getAll(); - verifyNoMoreInteractions(petDAOMock, petTypeDAOMock); - } - @Test public void shouldInsertDispatchCallToDAO() throws Exception { when(petDAOMock.insert(any(Pet.class))).thenReturn(123); - assertEquals(123, petRepository.insertPet(any(Pet.class))); + assertEquals(123, petRepository.insert(any(Pet.class))); verify(petDAOMock).insert(any(Pet.class)); verifyNoMoreInteractions(petDAOMock); } @@ -68,14 +60,14 @@ public void shouldInsertDispatchCallToDAO() throws Exception { @Test public void shouldUpdateDispatchCallToDAO() throws Exception { doNothing().when(petDAOMock).update(any(Pet.class)); - petRepository.updatePet(any(Pet.class)); + petRepository.update(any(Pet.class)); verify(petDAOMock).update(any(Pet.class)); } @Test public void shouldDeleteByIdDispatchCallToDAO() throws Exception { doNothing().when(petDAOMock).deleteById(anyInt()); - petRepository.delete(anyInt()); + petRepository.deleteById(anyInt()); verify(petDAOMock).deleteById(anyInt()); verifyNoMoreInteractions(petDAOMock); } @@ -83,7 +75,7 @@ public void shouldDeleteByIdDispatchCallToDAO() throws Exception { @Test public void shouldDeleteByOwnerIdDispatchCallToDAO() throws Exception { doNothing().when(petDAOMock).deleteByOwnerId(anyInt()); - petRepository.deletePetsByOwnerId(anyInt()); + petRepository.deleteByOwnerId(anyInt()); verify(petDAOMock).deleteByOwnerId(anyInt()); verifyNoMoreInteractions(petDAOMock); } diff --git a/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java index 88f3ac0..cbdae14 100644 --- a/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java @@ -28,7 +28,7 @@ public class PetTypeRepositoryTests { private PetTypeRepository petTypeRepository; @Test - public void shouldGetAllPetTypesDispatchCallToDAO() throws Exception { + public void shouldGetAllDispatchCallToDAO() throws Exception { when(petTypeDAOMock.getAll()).thenReturn(petTypeListMock); assertEquals(petTypeListMock, petTypeRepository.getAllTypes()); verify(petTypeDAOMock).getAll(); @@ -36,9 +36,9 @@ public void shouldGetAllPetTypesDispatchCallToDAO() throws Exception { } @Test - public void shouldGetPetTypeByIdDispatchCallToDAO() throws Exception { + public void shouldGetByIdDispatchCallToDAO() throws Exception { when(petTypeDAOMock.getById(anyInt())).thenReturn(petTypeMock); - assertEquals(petTypeMock, petTypeRepository.getPetTypeById(anyInt())); + assertEquals(petTypeMock, petTypeRepository.getById(anyInt())); verify(petTypeDAOMock).getById(anyInt()); verifyNoMoreInteractions(petTypeDAOMock); } diff --git a/src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java index 08a208e..4e46113 100644 --- a/src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/VisitRepositoryTests.java @@ -24,7 +24,7 @@ public class VisitRepositoryTests { @Test public void shouldInsertDispatchCallToDAO() throws Exception { when(visitDAOMock.insert(any(Visit.class))).thenReturn(123); - assertEquals(123, visitRepository.insertVisit(any(Visit.class))); + assertEquals(123, visitRepository.insert(any(Visit.class))); verify(visitDAOMock).insert(any(Visit.class)); verifyNoMoreInteractions(visitDAOMock); } @@ -32,7 +32,7 @@ public void shouldInsertDispatchCallToDAO() throws Exception { @Test public void shouldDeleteByIdDispatchCallToDAO() throws Exception { doNothing().when(visitDAOMock).deleteById(anyInt()); - visitRepository.delete(anyInt()); + visitRepository.deleteById(anyInt()); verify(visitDAOMock).deleteById(anyInt()); verifyNoMoreInteractions(visitDAOMock); } From dba26f6c347af79c52df9a9e71d0765b81522c62 Mon Sep 17 00:00:00 2001 From: PunCha Date: Sat, 20 Aug 2016 00:08:07 +0800 Subject: [PATCH 07/29] Unify DAO Tests naming convention --- .../puncha/integration/daos/OwnerDAOTest.java | 30 +++++++++---------- .../puncha/integration/daos/PetDAOTest.java | 26 ++++++++-------- .../integration/daos/PetTypeDAOTest.java | 6 ++-- .../puncha/integration/daos/VisitDAOTest.java | 10 +++---- 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java index 994feab..a6e4137 100644 --- a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java @@ -34,13 +34,13 @@ public class OwnerDAOTest { private OwnerDAO ownerDAO; @Test - public void shouldGetAllOwnersReturnAllOwnersList() throws Exception { + public void shouldGetAllReturnAllOwnersList() throws Exception { List owners = ownerDAO.getAll(); assertEquals(10, owners.size()); } @Test - public void shouldGetOwnerByIdReturnOwnerWhenOwnerExists() throws Exception { + public void shouldGetByIdReturnOwnerWhenOwnerExists() throws Exception { Owner owner = ownerDAO.getById(1); assertNotNull(owner); assertEquals(1, owner.getId()); @@ -48,13 +48,13 @@ public void shouldGetOwnerByIdReturnOwnerWhenOwnerExists() throws Exception { } @Test - public void shouldGetOwnerByIdReturnNullWhenOwnerNotExists() throws Exception { + public void shouldGetByIdReturnNullWhenOwnerNotExists() throws Exception { Owner owner = ownerDAO.getById(-1); assertNull(owner); } @Test - public void shouldGetOwnerWithPetsByIdReturnOwnerWithPetsWhenOwnerExists() throws Exception { + public void shouldGetByIdWithPetsReturnOwnerWithPetsWhenOwnerExists() throws Exception { Owner owner = ownerDAO.getByIdWithPets(1); assertNotNull(owner); assertEquals(1, owner.getId()); @@ -62,25 +62,25 @@ public void shouldGetOwnerWithPetsByIdReturnOwnerWithPetsWhenOwnerExists() throw } @Test - public void shouldGetOwnerWithPetsByIdReturnNullWhenOwnerNotExists() throws Exception { + public void shouldGetByIdWithPetsReturnNullWhenOwnerNotExists() throws Exception { Owner owner = ownerDAO.getByIdWithPets(-1); assertNull(owner); } @Test - public void shouldGetOwnersByFirstNameReturnMatchedOwnersList() throws Exception { + public void shouldFindByFirstNameReturnMatchedOwnersList() throws Exception { List owners = ownerDAO.findByFirstName("eT"); assertEquals(2, owners.size()); } @Test - public void shouldGetOwnersByFirstNameReturnEmptyListWhenOnMatchedOwners() throws Exception { + public void shouldFindByFirstNameReturnEmptyListWhenOnMatchedOwners() throws Exception { List owners = ownerDAO.findByFirstName("puncha"); assertTrue(owners.isEmpty()); } @Test - public void shouldInsertOwnerSuccessWhenOwnerIsValid() throws Exception { + public void shouldInsertSucceededWhenOwnerIsValid() throws Exception { Owner owner = new Owner(); owner.setFirstName("puncha"); owner.setLastName("feng"); @@ -90,20 +90,20 @@ public void shouldInsertOwnerSuccessWhenOwnerIsValid() throws Exception { } @Test(expected = ConstraintViolationException.class) - public void shouldInsertOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception { + public void shouldInsertThrowExceptionWhenOwnerIsInvalid() throws Exception { Owner owner = new Owner(); ownerDAO.insert(owner); } @Test(expected = PersistenceException.class) - public void shouldInsertOwnerThrowExceptionWhenOwnerIdIsNotDefault() throws Exception { + public void shouldInsertThrowExceptionWhenOwnerIdIsNotDefault() throws Exception { Owner owner = new Owner(); owner.setId(123); ownerDAO.insert(owner); } @Test - public void shouldUpdateOwnerSucceededWhenOwnerIsValid() { + public void shouldUpdateSucceededWhenOwnerIsValid() { Owner owner = ownerDAO.getById(1); owner.setFirstName("puncha"); ownerDAO.update(owner); @@ -112,7 +112,7 @@ public void shouldUpdateOwnerSucceededWhenOwnerIsValid() { } @Test(expected = ConstraintViolationException.class) - public void shouldUpdateOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception { + public void shouldUpdateThrowExceptionWhenOwnerIsInvalid() throws Exception { Owner owner = ownerDAO.getById(1); owner.setFirstName("AB"); ownerDAO.update(owner); @@ -123,7 +123,7 @@ public void shouldUpdateOwnerThrowExceptionWhenOwnerIsInvalid() throws Exception } @Test(expected = PersistenceException.class) - public void shouldUpdateOwnerThrowExceptionWhenOwnerNotExists() throws Exception { + public void shouldUpdateThrowExceptionWhenOwnerNotExists() throws Exception { Owner owner = ownerDAO.getById(1); owner.setId(123); ownerDAO.update(owner); @@ -134,13 +134,13 @@ public void shouldUpdateOwnerThrowExceptionWhenOwnerNotExists() throws Exception } @Test - public void shouldDeleteOwnerWhenOwnerExists() throws Exception { + public void shouldDeleteByIdWhenOwnerExists() throws Exception { ownerDAO.deleteById(1); assertEquals(9, ownerDAO.getAll().size()); } @Test(expected = EntityNotFoundException.class) - public void shouldDeleteOwnerThrowExceptionWhenOwnerNotExists() throws Exception { + public void shouldDeleteByIdThrowExceptionWhenOwnerNotExists() throws Exception { ownerDAO.deleteById(123); } } diff --git a/src/test/java/tk/puncha/integration/daos/PetDAOTest.java b/src/test/java/tk/puncha/integration/daos/PetDAOTest.java index aedcf48..91c5681 100644 --- a/src/test/java/tk/puncha/integration/daos/PetDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/PetDAOTest.java @@ -42,26 +42,26 @@ public void forceFlush() { } @Test - public void shouldGetAllPetsReturnAllPetsList() throws Exception { + public void shouldGetAllReturnAllPetsList() throws Exception { List Pets = petDAO.getAll(); assertEquals(13, Pets.size()); } @Test - public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { + public void shouldGetByIdReturnPetWhenPetExists() throws Exception { Pet pet = petDAO.getById(1); assertNotNull(pet); assertEquals(1, pet.getId()); } @Test - public void shouldGetPetByIdReturnNullWhenPetNotExists() throws Exception { + public void shouldGetByIdReturnNullWhenPetNotExists() throws Exception { Pet pet = petDAO.getById(-1); assertNull(pet); } @Test - public void shouldInsertPetSuccessWhenPetIsValid() throws Exception { + public void shouldInsertSucceededWhenPetIsValid() throws Exception { Pet pet = new Pet(); pet.setName("puncha"); pet.setType(petTypeDAO.getById(1)); @@ -71,20 +71,20 @@ public void shouldInsertPetSuccessWhenPetIsValid() throws Exception { } @Test(expected = ConstraintViolationException.class) - public void shouldInsertPetThrowExceptionWhenPetIsInvalid() throws Exception { + public void shouldInsertThrowExceptionWhenPetIsInvalid() throws Exception { Pet Pet = new Pet(); petDAO.insert(Pet); } @Test(expected = PersistenceException.class) - public void shouldInsertPetThrowExceptionWhenPetIdIsNotDefault() throws Exception { + public void shouldInsertThrowExceptionWhenPetIdIsNotDefault() throws Exception { Pet Pet = new Pet(); Pet.setId(123); petDAO.insert(Pet); } @Test - public void shouldUpdatePetSucceededWhenPetIsValid() { + public void shouldUpdateSucceededWhenPetIsValid() { Pet pet = petDAO.getById(1); pet.setName("puncha"); petDAO.update(pet); @@ -93,7 +93,7 @@ public void shouldUpdatePetSucceededWhenPetIsValid() { @Test(expected = ConstraintViolationException.class) - public void shouldUpdatePetThrowExceptionWhenPetIsInvalid() throws Exception { + public void shouldUpdateThrowExceptionWhenPetIsInvalid() throws Exception { Pet pet = petDAO.getById(1); pet.setName("AB"); petDAO.update(pet); @@ -101,7 +101,7 @@ public void shouldUpdatePetThrowExceptionWhenPetIsInvalid() throws Exception { } @Test(expected = PersistenceException.class) - public void shouldUpdatePetThrowExceptionWhenPetNotExists() throws Exception { + public void shouldUpdateThrowExceptionWhenPetNotExists() throws Exception { Pet pet = petDAO.getById(1); pet.setId(123); petDAO.update(pet); @@ -110,25 +110,25 @@ public void shouldUpdatePetThrowExceptionWhenPetNotExists() throws Exception { } @Test - public void shouldDeletePetWhenPetExists() throws Exception { + public void shouldDeleteByIdWhenPetExists() throws Exception { petDAO.deleteById(1); assertEquals(12, petDAO.getAll().size()); } @Test(expected = EntityNotFoundException.class) - public void shouldDeletePetThrowExceptionWhenPetNotExists() throws Exception { + public void shouldDeleteByIdThrowExceptionWhenPetNotExists() throws Exception { petDAO.deleteById(123); } @Test - public void shouldDeletePetsByOwnerIdDeletePetsWhenOwnerExists() { + public void shouldDeleteByOwnerIdDeletePetsWhenOwnerExists() { petDAO.deleteByOwnerId(3); // Eduardo has two pets assertEquals(11, petDAO.getAll().size()); } @Test(expected = EntityNotFoundException.class) - public void shouldDeletePetsByOwnerIdThrowExceptionWhenOwnerNotExists() { + public void shouldDeleteByOwnerIdThrowExceptionWhenOwnerNotExists() { petDAO.deleteByOwnerId(123); } } diff --git a/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java b/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java index 25331da..3baa643 100644 --- a/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/PetTypeDAOTest.java @@ -29,13 +29,13 @@ public class PetTypeDAOTest { private PetTypeDAO petTypeDAO; @Test - public void shouldGetAllPetTypesReturnAllPetTypesList() throws Exception { + public void shouldGetAllReturnAllPetTypesList() throws Exception { List Pets = petTypeDAO.getAll(); assertEquals(6, Pets.size()); } @Test - public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { + public void shouldGetByIdReturnPetWhenPetExists() throws Exception { PetType petType = petTypeDAO.getById(1); assertNotNull(petType); assertEquals(1, petType.getId()); @@ -43,7 +43,7 @@ public void shouldGetPetByIdReturnPetWhenPetExists() throws Exception { } @Test - public void shouldGetPetByIdReturnNullWhenPetNotExists() throws Exception { + public void shouldGetByIdReturnNullWhenPetNotExists() throws Exception { PetType petType = petTypeDAO.getById(-1); assertNull(petType); } diff --git a/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java b/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java index 90e20e8..6f2af7c 100644 --- a/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/VisitDAOTest.java @@ -35,7 +35,7 @@ public class VisitDAOTest { private VisitDAO visitDAO; @Test - public void shouldInsertVisitSuccessWhenVisitIsValid() throws Exception { + public void shouldInsertSucceededWhenVisitIsValid() throws Exception { Visit visit = new Visit(); visit.setVisitDate(Date.valueOf("2011-08-09")); visit.setDescription("A test visit"); @@ -45,25 +45,25 @@ public void shouldInsertVisitSuccessWhenVisitIsValid() throws Exception { } @Test(expected = ConstraintViolationException.class) - public void shouldInsertVisitThrowExceptionWhenVisitIsInvalid() throws Exception { + public void shouldInsertThrowExceptionWhenVisitIsInvalid() throws Exception { Visit Visit = new Visit(); visitDAO.insert(Visit); } @Test(expected = PersistenceException.class) - public void shouldInsertVisitThrowExceptionWhenVisitIdIsNotDefault() throws Exception { + public void shouldInsertThrowExceptionWhenVisitIdIsNotDefault() throws Exception { Visit Visit = new Visit(); Visit.setId(123); visitDAO.insert(Visit); } @Test - public void shouldDeleteVisitWhenVisitExists() throws Exception { + public void shouldDeleteByIdWhenVisitExists() throws Exception { visitDAO.deleteById(1); } @Test(expected = EntityNotFoundException.class) - public void shouldDeleteVisitThrowExceptionWhenVisitNotExists() throws Exception { + public void shouldDeleteByIdThrowExceptionWhenVisitNotExists() throws Exception { visitDAO.deleteById(123); } } From f57d56dd5b6f3091e94bf019d42d4d770bbb855a Mon Sep 17 00:00:00 2001 From: PunCha Date: Sat, 20 Aug 2016 02:02:41 +0800 Subject: [PATCH 08/29] Revisit Controller Unit Tests: refine and add more test cases (mainly for different content types) --- .../tk/puncha/controllers/PetController.java | 2 +- .../puncha/controllers/VisitController.java | 12 +- .../repositories/PetTypeRepository.java | 2 +- .../RestfulPetTypeController.java | 2 +- .../controllers/ErrorControllerTests.java | 2 +- .../controllers/OwnerControllerTests.java | 120 ++++++++++++++---- .../unit/controllers/PetControllerTests.java | 75 ++++++++--- .../controllers/VisitControllerTests.java | 28 ++-- .../repositories/PetTypeRepositoryTests.java | 2 +- 9 files changed, 171 insertions(+), 74 deletions(-) diff --git a/src/main/java/tk/puncha/controllers/PetController.java b/src/main/java/tk/puncha/controllers/PetController.java index deebe15..13f0e76 100644 --- a/src/main/java/tk/puncha/controllers/PetController.java +++ b/src/main/java/tk/puncha/controllers/PetController.java @@ -60,7 +60,7 @@ void initPetBinder(WebDataBinder binder) { @ModelAttribute("types") List getPetTypes() { logger.debug("getPetTypes()"); - return petTypeRepository.getAllTypes(); + return petTypeRepository.getAll(); } @ModelAttribute("owners") diff --git a/src/main/java/tk/puncha/controllers/VisitController.java b/src/main/java/tk/puncha/controllers/VisitController.java index 6e2c8e9..2f32bb6 100644 --- a/src/main/java/tk/puncha/controllers/VisitController.java +++ b/src/main/java/tk/puncha/controllers/VisitController.java @@ -3,7 +3,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import tk.puncha.models.Pet; @@ -20,11 +19,6 @@ public class VisitController { private final PetRepository petRepository; private final VisitRepository visitRepository; - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.setDisallowedFields("id"); - } - @Autowired public VisitController(PetRepository petRepository, VisitRepository visitRepository) { this.petRepository = petRepository; @@ -51,12 +45,12 @@ public ModelAndView initCreationForm() { @PostMapping("/new") public String processCreationForm(Pet pet, @ModelAttribute @Valid Visit visit, BindingResult bingResult) { if (bingResult.hasErrors()) { - return "visit/new"; - } + return "visit/new"; + } pet.getVisits().add(visit); visit.setPet(pet); petRepository.update(pet); return "redirect:/pets/{petId}"; -} + } } diff --git a/src/main/java/tk/puncha/repositories/PetTypeRepository.java b/src/main/java/tk/puncha/repositories/PetTypeRepository.java index 30f0d3d..7892f63 100644 --- a/src/main/java/tk/puncha/repositories/PetTypeRepository.java +++ b/src/main/java/tk/puncha/repositories/PetTypeRepository.java @@ -19,7 +19,7 @@ public PetTypeRepository(PetTypeDAO petTypeDAO) { this.petTypeDAO = petTypeDAO; } - public List getAllTypes() { + public List getAll() { return petTypeDAO.getAll(); } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java b/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java index 88773fc..906d9aa 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java @@ -31,6 +31,6 @@ public ErrorInfo handleException(Exception exception) { @GetMapping @JsonView(PetJsonView.class) public List query() { - return petTypeRepository.getAllTypes(); + return petTypeRepository.getAll(); } } diff --git a/src/test/java/tk/puncha/unit/controllers/ErrorControllerTests.java b/src/test/java/tk/puncha/unit/controllers/ErrorControllerTests.java index e8e04f2..8947233 100644 --- a/src/test/java/tk/puncha/unit/controllers/ErrorControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/ErrorControllerTests.java @@ -29,7 +29,7 @@ public void shouldReturnIndexPage() throws Exception { String exceptionMsg = new RuntimeException(ErrorController.DEFAULT_EXCEPTION).toString(); mockMvc.perform(get("/errors")) - .andExpect(status().is(200)) + .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attribute("exception", hasToString(exceptionMsg))); } diff --git a/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java b/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java index 64d65a8..e6c2865 100644 --- a/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/OwnerControllerTests.java @@ -1,11 +1,15 @@ package tk.puncha.unit.controllers; +import com.fasterxml.jackson.annotation.JsonView; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; 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.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @@ -15,8 +19,9 @@ import tk.puncha.models.Owner; import tk.puncha.repositories.OwnerRepository; import tk.puncha.validators.OwnerValidator; +import tk.puncha.views.json.view.OwnerJsonView; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import static org.mockito.Matchers.any; @@ -34,51 +39,121 @@ public class OwnerControllerTests { @Autowired private MockMvc mockMvc; + @Mock + private Owner ownerMock; + @Mock + private List ownerListMock; + @MockBean private OwnerRepository ownerRepository; @MockBean private OwnerValidator ownerValidator; @Test - public void shouldShowAllOwners() throws Exception { - List owners = new ArrayList<>(); - when(ownerRepository.getAll()).thenReturn(owners); + public void shouldShowAllOwnersInHtmlView() throws Exception { + when(ownerRepository.getAll()).thenReturn(ownerListMock); mockMvc.perform(get("/owners")) .andExpect(status().isOk()) .andExpect(view().name("owner/index")) - .andExpect(model().attributeExists("owners")); + .andExpect(model().attribute("owners", ownerListMock)); + verify(ownerRepository).getAll(); + } + + @Test + public void shouldShowAllOwnersInJsonView() throws Exception { + List ownerList = Collections.emptyList(); + when(ownerRepository.getAll()).thenReturn(ownerList); + + mockMvc.perform(get("/owners.json")) + .andExpect(status().isOk()) + .andExpect(view().name("owner/index")) + .andExpect(model().attribute(JsonView.class.getName(), OwnerJsonView.WithPets.class)) + .andExpect(model().attribute("owners", ownerList)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)); verify(ownerRepository).getAll(); } + @Test + @Ignore("The XML view is rendered by XmlViewResolver which has to be an integration test and I don't want!") + public void shouldShowAllOwnersInXml() throws Exception { + List ownerList = Collections.emptyList(); + when(ownerRepository.getAll()).thenReturn(ownerList); + + mockMvc.perform(get("/owners.xml")) + .andExpect(status().isOk()) + .andExpect(view().name("owner/index")) + .andExpect(model().attribute("owners", ownerList)) + .andExpect(content().contentType(MediaType.APPLICATION_XML)); + verify(ownerRepository).getAll(); + } + + @Test + public void shouldShowAllOwnersInPdfView() throws Exception { + List ownerList = Collections.emptyList(); + when(ownerRepository.getAll()).thenReturn(ownerList); + + mockMvc.perform(get("/owners.pdf")) + .andExpect(status().isOk()) + .andExpect(view().name("owner/index")) + .andExpect(model().attribute("owners", ownerList)); +// .andExpect(content().contentType(MediaType.APPLICATION_PDF)); // HACK: content type is not set + verify(ownerRepository).getAll(); + } + + @Test + public void shouldShowAllOwnersInExcelView() throws Exception { + List ownerList = Collections.emptyList(); + when(ownerRepository.getAll()).thenReturn(ownerList); + + mockMvc.perform(get("/owners.xls")) + .andExpect(status().isOk()) + .andExpect(view().name("owner/index")) + .andExpect(model().attribute("owners", ownerList)); +// .andExpect(content().contentType("application/vnd.ms-excel")); // HACK: content type is not set + verify(ownerRepository).getAll(); + } + + @Test + public void shouldShowAllOwnersInAtomFeedView() throws Exception { + List ownerList = Collections.emptyList(); + when(ownerRepository.getAll()).thenReturn(ownerList); + + mockMvc.perform(get("/owners.atom")) + .andExpect(status().isOk()) + .andExpect(view().name("owner/index")) + .andExpect(model().attribute("owners", ownerList)) + .andExpect(content().contentType(MediaType.APPLICATION_ATOM_XML)); + verify(ownerRepository).getAll(); + } + + @Test public void shouldShowOwnersMatchedByFirstName() throws Exception { - List owners = new ArrayList<>(); - when(ownerRepository.findByFirstName(anyString())).thenReturn(owners); + when(ownerRepository.findByFirstName(anyString())).thenReturn(ownerListMock); // search for George mockMvc.perform(get("/owners").param("search-first-name", "gEora")) .andExpect(status().isOk()) .andExpect(view().name("owner/index")) - .andExpect(model().attributeExists("owners")); + .andExpect(model().attribute("owners", ownerListMock)); verify(ownerRepository).findByFirstName("gEora"); } @Test public void shouldShowOwnerDetail() throws Exception { - Owner owner = mock(Owner.class); - when(ownerRepository.getByIdWithPets(1)).thenReturn(owner); - when(ownerValidator.supports(owner.getClass())).thenReturn(true); + when(ownerRepository.getByIdWithPets(1)).thenReturn(ownerMock); + when(ownerValidator.supports(ownerMock.getClass())).thenReturn(true); mockMvc.perform(get("/owners/1")) .andExpect(status().isOk()) .andExpect(view().name("owner/viewOrEdit")) - .andExpect(model().attribute("owner", owner)) + .andExpect(model().attribute("owner", ownerMock)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Readonly)); verify(ownerRepository).getByIdWithPets(1); // validator is called even if we return the model - verify(ownerValidator).supports(owner.getClass()); + verify(ownerValidator).supports(ownerMock.getClass()); } @Test @@ -118,7 +193,7 @@ public void shouldCreateOwnerAndShowOwnerDetail() throws Exception { .param("city", "Shanghai") .param("telephone", "1234567"); mockMvc.perform(req) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/owners/123")); // The following verification passes if remove @WebMvc, so // this should be a bug in Spring Boot. @@ -145,19 +220,18 @@ public void shouldFailToCreateOwnerWhenOwnerInformationIsIncomplete() throws Exc @Test public void shouldShowOwnerEditForm() throws Exception { - Owner owner = mock(Owner.class); - when(ownerRepository.getById(1)).thenReturn(owner); - when(ownerValidator.supports(owner.getClass())).thenReturn(true); + when(ownerRepository.getById(1)).thenReturn(ownerMock); + when(ownerValidator.supports(ownerMock.getClass())).thenReturn(true); mockMvc.perform(get("/owners/1/edit")) .andExpect(status().isOk()) .andExpect(view().name("owner/viewOrEdit")) - .andExpect(model().attribute("owner", owner)) + .andExpect(model().attribute("owner", ownerMock)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Edit)); verify(ownerRepository).getById(1); // validator is called even if we return the model - verify(ownerValidator).supports(owner.getClass()); + verify(ownerValidator).supports(ownerMock.getClass()); } @Test @@ -171,14 +245,14 @@ public void shouldUpdateOwnerAnsShowOwnerDetail() throws Exception { .param("city", "Shanghai") .param("telephone", "1234567"); mockMvc.perform(req) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/owners/123")); } @Test public void shouldFailToUpdateOwnerWhenOwnerIdIsInvalid() throws Exception { RuntimeException exception = new RuntimeException(); - doThrow(exception).when(ownerRepository).update(any()); + doThrow(exception).when(ownerRepository).update(any(Owner.class)); when(ownerValidator.supports(any())).thenReturn(true); MockHttpServletRequestBuilder req = post("/owners/new") @@ -189,13 +263,13 @@ public void shouldFailToUpdateOwnerWhenOwnerIdIsInvalid() throws Exception { .andExpect(status().isOk()) .andExpect(view().name("exception/default")) .andExpect(model().attribute("exception", exception)); -// verify(ownerRepository).update(any()); +// verify(ownerRepository).update(any(Owner.class)); } @Test public void shouldDeleteOwnerAndShowAllOwners() throws Exception { mockMvc.perform(get("/owners/1/delete")) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/owners")); verify(ownerRepository).deleteById(1); } diff --git a/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java b/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java index 03047da..b6ee320 100644 --- a/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java @@ -2,6 +2,7 @@ import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -21,6 +22,7 @@ import tk.puncha.repositories.PetRepository; import tk.puncha.repositories.PetTypeRepository; +import java.util.Collections; import java.util.List; import static org.mockito.Mockito.*; @@ -37,6 +39,19 @@ public class PetControllerTests { @Autowired private MockMvc mockMvc; + @Mock + private Pet petMock; + @Mock + private List petListMock; + @Mock + private Owner ownerMock; + @Mock + private PetType petTypeMock; + @Mock + private List ownerListMock; + @Mock + private List petTypeListMock; + @MockBean private PetRepository petRepository; @MockBean @@ -49,28 +64,49 @@ public class PetControllerTests { private PetTypeFormatter petTypeFormatter; @Test - public void shouldShowAllPets() throws Exception { - List pets = mock(List.class); - when(petRepository.getAllPets()).thenReturn(pets); + public void shouldShowAllPetsInHtml() throws Exception { + when(petRepository.getAllPets()).thenReturn(petListMock); mockMvc.perform(get("/pets")) .andExpect(status().isOk()) .andExpect(view().name("pet/index")) - .andExpect(model().attribute("pets", pets)); +// .andExpect(content().contentType(MediaType.TEXT_HTML)) // it is NOT SET, why? + .andExpect(model().attribute("pets", petListMock)); + verify(petRepository).getAllPets(); + } + + @Test + public void shouldShowAllPetsInXml() throws Exception { + when(petRepository.getAllPets()).thenReturn(Collections.emptyList()); + + mockMvc.perform(get("/pets.xml")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/xml;charset=UTF-8")); + verify(petRepository).getAllPets(); + } + + @Test + public void shouldShowAllPetsInJson() throws Exception { + when(petRepository.getAllPets()).thenReturn(Collections.emptyList()); + + mockMvc.perform(get("/pets.json")) + .andExpect(status().isOk()) + .andExpect(content().contentType("application/json;charset=UTF-8")); verify(petRepository).getAllPets(); } @Test public void shouldShowPetDetail() throws Exception { - Pet pet = mock(Pet.class); - when(petRepository.getById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(petMock); + when(ownerRepository.getAll()).thenReturn(ownerListMock); + when(petTypeRepository.getAll()).thenReturn(petTypeListMock); mockMvc.perform(get("/pets/1")) .andExpect(status().isOk()) .andExpect(view().name("pet/viewOrEdit")) - .andExpect(model().attributeExists("owners")) - .andExpect(model().attributeExists("types")) - .andExpect(model().attribute("pet", pet)) + .andExpect(model().attribute("owners", ownerListMock)) + .andExpect(model().attribute("types", petTypeListMock)) + .andExpect(model().attribute("pet", petMock)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Readonly)); verify(petRepository).getById(1); @@ -102,16 +138,16 @@ public void shouldShowPetCreationForm() throws Exception { @Test public void shouldCreatePet() throws Exception { when(petRepository.insert(any())).thenReturn(123); - when(petTypeFormatter.parse(any(), any())).thenReturn(mock(PetType.class)); - when(ownerFormatter.parse(any(), any())).thenReturn(mock(Owner.class)); + when(ownerFormatter.parse(any(), any())).thenReturn(ownerMock); + when(petTypeFormatter.parse(any(), any())).thenReturn(petTypeMock); MockHttpServletRequestBuilder req = post("/pets/new") .sessionAttr("id", "-1") - .param("id", "111") // cheat + .param("id", "111") // cheat the server .param("name", "puncha") .param("owner", "1") .param("type", "1"); mockMvc.perform(req) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/pets/123")); } @@ -135,15 +171,14 @@ public void shouldFailToCreatePetWhenPetInformationIsIncomplete() throws Excepti @Test public void shouldShowPetEditForm() throws Exception { - Pet pet = mock(Pet.class); - when(petRepository.getById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(petMock); mockMvc.perform(get("/pets/1/edit")) .andExpect(status().isOk()) .andExpect(view().name("pet/viewOrEdit")) .andExpect(model().attributeExists("owners")) .andExpect(model().attributeExists("types")) - .andExpect(model().attribute("pet", pet)) + .andExpect(model().attribute("pet", petMock)) .andExpect(model().attribute("mode", ControllerBase.FormMode.Edit)); verify(petRepository).getById(1); @@ -151,22 +186,22 @@ public void shouldShowPetEditForm() throws Exception { @Test public void shouldUpdatePetAnsShowPetDetail() throws Exception { - when(petTypeFormatter.parse(any(), any())).thenReturn(mock(PetType.class)); - when(ownerFormatter.parse(any(), any())).thenReturn(mock(Owner.class)); + when(petTypeFormatter.parse(any(), any())).thenReturn(petTypeMock); + when(ownerFormatter.parse(any(), any())).thenReturn(ownerMock); MockHttpServletRequestBuilder req = post("/pets/new") .sessionAttr("id", "123") .param("id", "456") // cheat the server .param("owner", "1") .param("type", "1"); mockMvc.perform(req) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/pets/123")); // make sure the server not cheated } @Test public void shouldDeletePetAndShowAllPets() throws Exception { mockMvc.perform(get("/pets/1/delete")) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/pets")); } diff --git a/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java b/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java index 25dcaf4..0d718fa 100644 --- a/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/VisitControllerTests.java @@ -2,6 +2,7 @@ import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; @@ -29,6 +30,8 @@ public class VisitControllerTests { @Autowired private MockMvc mockMvc; + @Mock + private Pet petMock; @MockBean private PetRepository petRepository; @MockBean @@ -36,35 +39,32 @@ public class VisitControllerTests { @Test public void shouldShowVisitCreationForm() throws Exception { - Pet pet = mock(Pet.class); - when(petRepository.getById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(petMock); mockMvc.perform(get("/pets/1/visits/new")) .andExpect(status().isOk()) .andExpect(view().name("visit/new")) - .andExpect(model().attribute("pet", pet)) + .andExpect(model().attribute("pet", petMock)) .andExpect(model().attributeExists("visit")); } @Test public void shouldCreateVisitAndShowPetDetail() throws Exception { - Pet pet = mock(Pet.class); - when(petRepository.getById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(petMock); MockHttpServletRequestBuilder req = post("/pets/1/visits/new") .param("description", "...") .param("visitDate", "1999-09-09"); mockMvc.perform(req) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/pets/1")); } @Test public void shouldFailToCreateVisitWhenVisitInformationIsIncomplete() throws Exception { - Pet pet = mock(Pet.class); - when(petRepository.getById(1)).thenReturn(pet); + when(petRepository.getById(1)).thenReturn(petMock); mockMvc.perform(post("/pets/1/visits/new")) .andExpect(status().isOk()) .andExpect(view().name("visit/new")) - .andExpect(model().attribute("pet", pet)) + .andExpect(model().attribute("pet", petMock)) .andExpect(model().attributeHasErrors("visit")) .andExpect(model().attributeHasFieldErrorCode("visit", "visitDate", "NotNull")); } @@ -73,14 +73,14 @@ public void shouldFailToCreateVisitWhenVisitInformationIsIncomplete() throws Exc public void shouldDeleteVisitAndShowPetDetail() throws Exception { when(petRepository.getById(1)).thenReturn(mock(Pet.class)); mockMvc.perform(get("/pets/1/visits/2/delete")) - .andExpect(status().is(302)) + .andExpect(status().isFound()) .andExpect(redirectedUrl("/pets/1")); verify(visitRepository).deleteById(2); } @Test public void shouldFailToDeleteVisitWhenVisitDoesNotExist() throws Exception { - when(petRepository.getById(1)).thenReturn(mock(Pet.class)); + when(petRepository.getById(1)).thenReturn(petMock); RuntimeException exception = new RuntimeException(); doThrow(exception).when(visitRepository).deleteById(2); mockMvc.perform(get("/pets/1/visits/2/delete")) @@ -99,10 +99,4 @@ public void shouldFailToDeleteVisitWhenPetDoesNotExist() throws Exception { .andExpect(model().attributeExists("exception")); verify(petRepository).getById(1); } - - @Test - public void shouldChangePetIdWouldNotAffactReadPetId() throws Exception { - - - } } diff --git a/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java index cbdae14..7d94396 100644 --- a/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/PetTypeRepositoryTests.java @@ -30,7 +30,7 @@ public class PetTypeRepositoryTests { @Test public void shouldGetAllDispatchCallToDAO() throws Exception { when(petTypeDAOMock.getAll()).thenReturn(petTypeListMock); - assertEquals(petTypeListMock, petTypeRepository.getAllTypes()); + assertEquals(petTypeListMock, petTypeRepository.getAll()); verify(petTypeDAOMock).getAll(); verifyNoMoreInteractions(petTypeDAOMock); } From fef664a3f5f00fbb12a12f6793ed2365251ab757 Mon Sep 17 00:00:00 2001 From: PunCha Date: Sat, 20 Aug 2016 02:08:56 +0800 Subject: [PATCH 09/29] Remove Integration tests of repositories and update OwnerDAOTest --- .../puncha/integration/daos/OwnerDAOTest.java | 5 ++ .../repositories/OwnerRepositoryTests.java | 88 ------------------- .../repositories/PetRepositoryTests.java | 5 -- .../repositories/PetTypeRepositoryTests.java | 5 -- .../repositories/VisitRepositoryTests.java | 5 -- 5 files changed, 5 insertions(+), 103 deletions(-) delete mode 100644 src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java delete mode 100644 src/test/java/tk/puncha/integration/repositories/PetRepositoryTests.java delete mode 100644 src/test/java/tk/puncha/integration/repositories/PetTypeRepositoryTests.java delete mode 100644 src/test/java/tk/puncha/integration/repositories/VisitRepositoryTests.java diff --git a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java index a6e4137..d373093 100644 --- a/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java +++ b/src/test/java/tk/puncha/integration/daos/OwnerDAOTest.java @@ -44,6 +44,11 @@ public void shouldGetByIdReturnOwnerWhenOwnerExists() throws Exception { Owner owner = ownerDAO.getById(1); assertNotNull(owner); assertEquals(1, owner.getId()); + assertEquals("George", owner.getFirstName()); + assertEquals("Franklin", owner.getLastName()); + assertEquals("110 W. Liberty St.", owner.getAddress()); + assertEquals("Madison", owner.getCity()); + assertEquals("6085551023", owner.getTelephone()); assertFalse(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); } diff --git a/src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java b/src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java deleted file mode 100644 index c4cb56f..0000000 --- a/src/test/java/tk/puncha/integration/repositories/OwnerRepositoryTests.java +++ /dev/null @@ -1,88 +0,0 @@ -package tk.puncha.integration.repositories; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import tk.puncha.Application; -import tk.puncha.models.Owner; -import tk.puncha.repositories.OwnerRepository; - -import javax.persistence.Persistence; -import javax.validation.ConstraintViolationException; -import java.util.List; - -import static org.junit.Assert.*; - -@RunWith(SpringRunner.class) -@AutoConfigureTestDatabase -@TestPropertySource(locations="classpath:test.properties") -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) -public class OwnerRepositoryTests{ - @Configuration - @EnableAutoConfiguration() - static class Dummy extends Application { - } - - @Autowired - private OwnerRepository ownerRepository; - - @Test - public void shouldGetAllOwnersReturnListOfOwners() throws Exception { - List allOwners = ownerRepository.getAll(); - assertEquals(10, allOwners.size()); - } - - @Test - public void shouldGetOwnerByIdReturnAnOwnerIfExists() throws Exception { - Owner owner = ownerRepository.getById(1); - assertEquals(1, owner.getId()); - assertEquals("George", owner.getFirstName()); - assertEquals("Franklin", owner.getLastName()); - assertEquals("110 W. Liberty St.", owner.getAddress()); - assertEquals("Madison", owner.getCity()); - assertEquals("6085551023", owner.getTelephone()); - assertFalse(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); - } - - @Test - public void shouldGetOwnerByIdReturnNullIfOwnerNotExists() throws Exception { - Owner owner = ownerRepository.getById(-1); - assertNull(owner); - } - - @Test - public void shouldGetOwnerWithPetsByIdReturnInitializedPetsCollection() throws Exception { - Owner owner = ownerRepository.getByIdWithPets(1); - assertEquals(1, owner.getId()); - assertTrue(Persistence.getPersistenceUtil().isLoaded(owner.getPets())); - } - - @Test - public void shouldInsertOwner() throws Exception { - Owner owner = new Owner(); - owner.setFirstName("puncha"); - owner.setLastName("feng"); - ownerRepository.insert(owner); - assertNotNull(ownerRepository.getById(owner.getId())); - } - - @Test(expected = ConstraintViolationException.class) - public void shouldInsertOwnerThrowIfOwnerIsInvalid() throws Exception { - Owner owner = new Owner(); - ownerRepository.insert(owner); - } - - @Test - public void shouldUpdateOwner() throws Exception { - Owner owner = ownerRepository.getById(2); - owner.setFirstName("puncha"); - ownerRepository.update(owner); - assertEquals("puncha", ownerRepository.getById(2).getFirstName()); - } -} diff --git a/src/test/java/tk/puncha/integration/repositories/PetRepositoryTests.java b/src/test/java/tk/puncha/integration/repositories/PetRepositoryTests.java deleted file mode 100644 index df200f0..0000000 --- a/src/test/java/tk/puncha/integration/repositories/PetRepositoryTests.java +++ /dev/null @@ -1,5 +0,0 @@ -package tk.puncha.integration.repositories; - -// TODO: Implement me! -public class PetRepositoryTests { -} \ No newline at end of file diff --git a/src/test/java/tk/puncha/integration/repositories/PetTypeRepositoryTests.java b/src/test/java/tk/puncha/integration/repositories/PetTypeRepositoryTests.java deleted file mode 100644 index a7c216c..0000000 --- a/src/test/java/tk/puncha/integration/repositories/PetTypeRepositoryTests.java +++ /dev/null @@ -1,5 +0,0 @@ -package tk.puncha.integration.repositories; - -// TODO: Implement me! -public class PetTypeRepositoryTests { -} \ No newline at end of file diff --git a/src/test/java/tk/puncha/integration/repositories/VisitRepositoryTests.java b/src/test/java/tk/puncha/integration/repositories/VisitRepositoryTests.java deleted file mode 100644 index d906b5f..0000000 --- a/src/test/java/tk/puncha/integration/repositories/VisitRepositoryTests.java +++ /dev/null @@ -1,5 +0,0 @@ -package tk.puncha.integration.repositories; - -// TODO: Implement me! -public class VisitRepositoryTests { -} \ No newline at end of file From 013fcbbff56e0dd32129a20fa9edfe3ca2c1aa1f Mon Sep 17 00:00:00 2001 From: PunCha Date: Sat, 20 Aug 2016 18:50:52 +0800 Subject: [PATCH 10/29] Add unit test for all restful controllers --- .../tk/puncha/controllers/PetController.java | 4 +- .../tk/puncha/repositories/PetRepository.java | 2 +- .../RestfulOwnerController.java | 28 ++- .../RestfulPetController.java | 24 ++- .../RestfulPetTypeController.java | 14 +- .../RestfulVisitController.java | 10 +- src/test/java/tk/puncha/TestUtil.java | 26 ++- .../unit/controllers/PetControllerTests.java | 12 +- .../tk/puncha/unit/models/VisitTests.java | 11 +- .../unit/repositories/PetRepositoryTests.java | 2 +- .../RestfulOwnerControllerTests.java | 197 ++++++++++++++++++ .../RestfulPetControllerTests.java | 182 ++++++++++++++++ .../RestfulPetTypeControllerTests.java | 63 ++++++ 13 files changed, 536 insertions(+), 39 deletions(-) create mode 100644 src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java create mode 100644 src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java create mode 100644 src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java diff --git a/src/main/java/tk/puncha/controllers/PetController.java b/src/main/java/tk/puncha/controllers/PetController.java index 13f0e76..7d68919 100644 --- a/src/main/java/tk/puncha/controllers/PetController.java +++ b/src/main/java/tk/puncha/controllers/PetController.java @@ -72,7 +72,7 @@ List getOwners() { @GetMapping(value = {"", "/index", "/default"}, produces = MediaType.TEXT_HTML_VALUE) public ModelAndView htmlIndex() { logger.debug("index()"); - List petViews = petRepository.getAllPets(); + List petViews = petRepository.getAll(); return new ModelAndView("pet/index", "pets", petViews); } @@ -148,7 +148,7 @@ private ModelAndView createFormModelView(Pet pet, FormMode mode) { @ResponseStatus(HttpStatus.OK) @ResponseBody public List getAllPets() { - return petRepository.getAllPets(); + return petRepository.getAll(); } } diff --git a/src/main/java/tk/puncha/repositories/PetRepository.java b/src/main/java/tk/puncha/repositories/PetRepository.java index da813ba..3a3a679 100644 --- a/src/main/java/tk/puncha/repositories/PetRepository.java +++ b/src/main/java/tk/puncha/repositories/PetRepository.java @@ -24,7 +24,7 @@ public PetRepository(PetDAO petDAO, PetTypeDAO petTypeDAO) { } @Transactional(readOnly = true) - public List getAllPets() { + public List getAll() { return petDAO.getAll(); } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java b/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java index d521100..55e5eb1 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulOwnerController.java @@ -13,14 +13,13 @@ import tk.puncha.validators.OwnerValidator; import tk.puncha.views.json.view.OwnerJsonView; +import javax.persistence.EntityNotFoundException; import javax.validation.Valid; import java.util.List; @RestController // Includes @ResponseBody @RequestMapping(path = "/api/owners", produces = MediaType.APPLICATION_JSON_VALUE) public class RestfulOwnerController { - - private final OwnerRepository ownerRepository; private final OwnerValidator ownerValidator; @@ -54,13 +53,11 @@ public List getAllOwners(@RequestParam(required = false) String firstName @GetMapping("{ownerId}") @JsonView(OwnerJsonView.WithPets.class) - public Owner getOwner(@PathVariable int ownerId) { - return ownerRepository.getByIdWithPets(ownerId); - } - - @DeleteMapping("{ownerId}") - public void deleteOwner(@PathVariable int ownerId) { - ownerRepository.deleteById(ownerId); + public ResponseEntity getOwner(@PathVariable int ownerId) { + Owner owner = ownerRepository.getByIdWithPets(ownerId); + if (owner == null) + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + return ResponseEntity.ok(owner); } @PostMapping @@ -71,7 +68,7 @@ public ResponseEntity createOwner(@Valid @RequestBody Owner owner, BindingResult return ResponseEntity.badRequest().body(errorInfo); } ownerRepository.insert(owner); - return ResponseEntity.ok(owner); + return new ResponseEntity(HttpStatus.CREATED); } @PostMapping("{ownerId}") @@ -86,4 +83,15 @@ public ResponseEntity updateOwner(@Valid @RequestBody Owner owner, BindingResult ownerRepository.update(owner); return ResponseEntity.noContent().build(); } + + @DeleteMapping("{ownerId}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public ResponseEntity deleteOwner(@PathVariable int ownerId) { + try { + ownerRepository.deleteById(ownerId); + return new ResponseEntity(HttpStatus.NO_CONTENT); + } catch (EntityNotFoundException e) { + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + } } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java b/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java index 762c28e..463a137 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulPetController.java @@ -4,12 +4,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import tk.puncha.models.Pet; import tk.puncha.repositories.PetRepository; import tk.puncha.views.json.view.PetJsonView; +import javax.persistence.EntityNotFoundException; import javax.validation.Valid; import java.util.List; @@ -32,17 +34,21 @@ public ErrorInfo handleException(Exception exception) { @GetMapping @JsonView(PetJsonView.class) - public List query() { - return petRepository.getAllPets(); + public List getAll() { + return petRepository.getAll(); } @GetMapping("{id}") @JsonView(PetJsonView.class) - public Pet get(@PathVariable int id) { - return petRepository.getById(id); + public ResponseEntity get(@PathVariable int id) { + Pet pet = petRepository.getById(id); + if (pet == null) + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + return ResponseEntity.ok(pet); } @PostMapping + @ResponseStatus(HttpStatus.CREATED) public void create(@Valid @RequestBody Pet pet, BindingResult bindingResult) { if (bindingResult.hasErrors()) { throw new RuntimeException("Invalid data."); @@ -51,6 +57,7 @@ public void create(@Valid @RequestBody Pet pet, BindingResult bindingResult) { } @PostMapping("{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) public void update(@Valid @RequestBody Pet pet, BindingResult bindingResult) { if (bindingResult.hasErrors()) { throw new RuntimeException("Invalid data."); @@ -59,7 +66,12 @@ public void update(@Valid @RequestBody Pet pet, BindingResult bindingResult) { } @DeleteMapping("{id}") - public void delete(@PathVariable int id) { - petRepository.deleteById(id); + public ResponseEntity delete(@PathVariable int id) { + try { + petRepository.deleteById(id); + return ResponseEntity.noContent().build(); + } catch (EntityNotFoundException e) { + return ResponseEntity.notFound().build(); + } } } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java b/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java index 906d9aa..c4c95dd 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulPetTypeController.java @@ -2,9 +2,10 @@ import com.fasterxml.jackson.annotation.JsonView; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; import tk.puncha.models.PetType; import tk.puncha.repositories.PetTypeRepository; import tk.puncha.views.json.view.PetJsonView; @@ -21,16 +22,9 @@ public RestfulPetTypeController(PetTypeRepository petTypeRepository) { this.petTypeRepository = petTypeRepository; } - @ExceptionHandler(Exception.class) - @ResponseStatus(value = HttpStatus.BAD_REQUEST) - @ResponseBody - public ErrorInfo handleException(Exception exception) { - return new ErrorInfo(String.format("Unhandled exception %s", exception.getMessage())); - } - @GetMapping @JsonView(PetJsonView.class) - public List query() { + public List getAll() { return petTypeRepository.getAll(); } } diff --git a/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java b/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java index 4a1faed..074fdbf 100644 --- a/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java +++ b/src/main/java/tk/puncha/restfulControllers/RestfulVisitController.java @@ -9,6 +9,7 @@ import tk.puncha.repositories.PetRepository; import tk.puncha.repositories.VisitRepository; +import javax.persistence.EntityNotFoundException; import javax.validation.Valid; @RestController // Includes @ResponseBody @@ -36,13 +37,20 @@ public Pet getPet(@PathVariable int petId) { } @PostMapping + @ResponseStatus(HttpStatus.CREATED) public void create(Pet pet, @Valid @RequestBody Visit visit) { + if(pet == null) + throw new EntityNotFoundException("Pet doesn't exist."); visit.setPet(pet); visitRepository.insert(visit); } @DeleteMapping("{id}") - public void delete(@PathVariable int id) { + @ResponseStatus(HttpStatus.NO_CONTENT) + public void delete(Pet pet, @PathVariable int id) { + if(pet == null) + throw new EntityNotFoundException("Pet doesn't exist."); + visitRepository.deleteById(id); } } diff --git a/src/test/java/tk/puncha/TestUtil.java b/src/test/java/tk/puncha/TestUtil.java index d01c992..dc66504 100644 --- a/src/test/java/tk/puncha/TestUtil.java +++ b/src/test/java/tk/puncha/TestUtil.java @@ -1,5 +1,9 @@ package tk.puncha; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; @@ -26,7 +30,6 @@ public static Validator createValidator() { return localValidator; } - public static void assertViolation( T objToValidate, String property, Object invalidValue, String message) { Set> violations = createValidator().validate(objToValidate); @@ -36,4 +39,25 @@ public static void assertViolation( assertEquals(invalidValue, violation.getInvalidValue()); assertEquals(message, violation.getMessage()); } + + + public static byte[] objectToJsonBytes(Object object) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsBytes(object); + } + + public static String objectToJsonString(Object object) throws JsonProcessingException { + return objectToJsonString(object, null); + } + + public static String objectToJsonString(Object object, Class viewClass) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + if (viewClass != null) { + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); + mapper.setConfig(mapper.getSerializationConfig().withView(viewClass)); + } + return mapper.writeValueAsString(object); + } } diff --git a/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java b/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java index b6ee320..5039d5c 100644 --- a/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java +++ b/src/test/java/tk/puncha/unit/controllers/PetControllerTests.java @@ -65,34 +65,34 @@ public class PetControllerTests { @Test public void shouldShowAllPetsInHtml() throws Exception { - when(petRepository.getAllPets()).thenReturn(petListMock); + when(petRepository.getAll()).thenReturn(petListMock); mockMvc.perform(get("/pets")) .andExpect(status().isOk()) .andExpect(view().name("pet/index")) // .andExpect(content().contentType(MediaType.TEXT_HTML)) // it is NOT SET, why? .andExpect(model().attribute("pets", petListMock)); - verify(petRepository).getAllPets(); + verify(petRepository).getAll(); } @Test public void shouldShowAllPetsInXml() throws Exception { - when(petRepository.getAllPets()).thenReturn(Collections.emptyList()); + when(petRepository.getAll()).thenReturn(Collections.emptyList()); mockMvc.perform(get("/pets.xml")) .andExpect(status().isOk()) .andExpect(content().contentType("application/xml;charset=UTF-8")); - verify(petRepository).getAllPets(); + verify(petRepository).getAll(); } @Test public void shouldShowAllPetsInJson() throws Exception { - when(petRepository.getAllPets()).thenReturn(Collections.emptyList()); + when(petRepository.getAll()).thenReturn(Collections.emptyList()); mockMvc.perform(get("/pets.json")) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")); - verify(petRepository).getAllPets(); + verify(petRepository).getAll(); } @Test diff --git a/src/test/java/tk/puncha/unit/models/VisitTests.java b/src/test/java/tk/puncha/unit/models/VisitTests.java index 3156e4f..ec2522d 100644 --- a/src/test/java/tk/puncha/unit/models/VisitTests.java +++ b/src/test/java/tk/puncha/unit/models/VisitTests.java @@ -6,9 +6,11 @@ import tk.puncha.models.Visit; import javax.validation.ConstraintViolation; +import java.sql.Date; import java.util.Set; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; public class VisitTests { @@ -32,4 +34,11 @@ public void shouldDefaultVisitNotValidate() throws Exception { Set> violations = TestUtil.createValidator().validate(visit); assertEquals(1, violations.size()); // visitDate } + + @Test + public void shouldVisitValidate() throws Exception { + visit.setVisitDate(new Date(2016,6,6)); + Set> violations = TestUtil.createValidator().validate(visit); + assertEquals(0, violations.size()); + } } diff --git a/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java b/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java index 35064c3..68755d0 100644 --- a/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java +++ b/src/test/java/tk/puncha/unit/repositories/PetRepositoryTests.java @@ -36,7 +36,7 @@ public class PetRepositoryTests { @Test public void shouldGetAllDispatchCallToDAO() throws Exception { when(petDAOMock.getAll()).thenReturn(petListMock); - assertEquals(petListMock, petRepository.getAllPets()); + assertEquals(petListMock, petRepository.getAll()); verify(petDAOMock).getAll(); verifyNoMoreInteractions(petDAOMock); } diff --git a/src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java b/src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java new file mode 100644 index 0000000..74b29e5 --- /dev/null +++ b/src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java @@ -0,0 +1,197 @@ +package tk.puncha.unit.restfulControllers; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import tk.puncha.TestUtil; +import tk.puncha.models.Owner; +import tk.puncha.repositories.OwnerRepository; +import tk.puncha.restfulControllers.RestfulOwnerController; +import tk.puncha.validators.OwnerValidator; +import tk.puncha.views.json.view.OwnerJsonView; + +import javax.persistence.EntityNotFoundException; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@AutoConfigureTestDatabase +@TestPropertySource(locations = {"/test.properties", "/unit-test.properties"}) +@RunWith(SpringRunner.class) +@WebMvcTest(RestfulOwnerController.class) +public class RestfulOwnerControllerTests { + @Autowired + private MockMvc mockMvc; + + @Mock + private Owner ownerMock; + + @MockBean + private OwnerValidator ownerValidator; + @MockBean + private OwnerRepository ownerRepository; + + private Owner createInvalidOwner() { + return new Owner(); + } + + private Owner createValidOwner() { + return new Owner() {{ + setId(1); + setFirstName("PunCha"); + setLastName("Feng"); + setAddress("Shanghai"); + }}; + } + + @Before + public void makeValidatorSupportsAnyType() { + when(ownerValidator.supports(any())).thenReturn(true); + } + + @Test + public void shouldReturnAllOwnersList() throws Exception { + List ownerList = Collections.singletonList(createValidOwner()); + when(ownerRepository.getAll()).thenReturn(ownerList); + + mockMvc.perform(get("/api/owners").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(content().json(TestUtil.objectToJsonString(ownerList, OwnerJsonView.class))); + + verify(ownerRepository).getAll(); + verifyNoMoreInteractions(ownerRepository); + } + + @Test + public void shouldReturnOwnersListFilterByFirstName() throws Exception { + List ownerList = Collections.singletonList(createValidOwner()); + when(ownerRepository.findByFirstName("puncha")).thenReturn(ownerList); + + mockMvc.perform(get("/api/owners?firstName=puncha").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(content().json(TestUtil.objectToJsonString(ownerList, OwnerJsonView.class))); + + verify(ownerRepository).findByFirstName("puncha"); + verifyNoMoreInteractions(ownerRepository); + } + + @Test + public void shouldReturnOwnerWhenOwnerExists() throws Exception { + Owner owner = createValidOwner(); + when(ownerRepository.getByIdWithPets(1)).thenReturn(owner); + + System.out.printf(TestUtil.objectToJsonString(owner)); + + mockMvc.perform(get("/api/owners/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(content().json(TestUtil.objectToJsonString(owner, OwnerJsonView.class))); + } + + @Test + public void shouldReturnNotFoundWhenOwnerNotExists() throws Exception { + mockMvc.perform(get("/api/owners/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + + verify(ownerRepository).getByIdWithPets(1); + verifyNoMoreInteractions(ownerRepository); + } + + @Test + public void shouldCreateOwnerWhenOwnerIsValid() throws Exception { + Owner owner = createValidOwner(); + when(ownerRepository.insert(owner)).thenReturn(1); + + MockHttpServletRequestBuilder req = post("/api/owners") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(owner)); + + mockMvc.perform(req) + .andExpect(status().isCreated()); + } + + @Test + public void shouldFailToCreateVisitWhenOwnerIsInvalid() throws Exception { + MockHttpServletRequestBuilder req = post("/api/owners") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createInvalidOwner())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + + verifyZeroInteractions(ownerRepository); + } + + @Test + public void shouldUpdateOwnerWhenOwnerIsValid() throws Exception { + MockHttpServletRequestBuilder req = post("/api/owners/1") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createValidOwner())); + + mockMvc.perform(req) + .andExpect(status().isNoContent()); + } + + @Test + public void shouldFailToUpdateOwnerWhenOwnerIsInvalid() throws Exception { + MockHttpServletRequestBuilder req = post("/api/owners/1") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createInvalidOwner())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + } + + + @Test + public void shouldFailToUpdateOwnerWhenOwnerNotExist() throws Exception { + doThrow(EntityNotFoundException.class).when(ownerRepository).update(any(Owner.class)); + MockHttpServletRequestBuilder req = post("/api/owners/1") + .accept(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createValidOwner())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + } + + @Test + public void shouldDeleteOwnerWhenOwnerExists() throws Exception { + mockMvc.perform(delete("/api/owners/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + verify(ownerRepository).deleteById(1); + verifyNoMoreInteractions(ownerRepository); + } + + @Test + public void shouldFailToDeleteOwnerWhenOwnerNotExist() throws Exception { + doThrow(EntityNotFoundException.class).when(ownerRepository).deleteById(1); + + mockMvc.perform(delete("/api/owners/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + + verify(ownerRepository).deleteById(1); + verifyNoMoreInteractions(ownerRepository); + } +} diff --git a/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java new file mode 100644 index 0000000..823d0dd --- /dev/null +++ b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java @@ -0,0 +1,182 @@ +package tk.puncha.unit.restfulControllers; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import tk.puncha.TestUtil; +import tk.puncha.models.Owner; +import tk.puncha.models.Pet; +import tk.puncha.models.PetType; +import tk.puncha.repositories.PetRepository; +import tk.puncha.restfulControllers.RestfulPetController; +import tk.puncha.views.json.view.PetJsonView; + +import javax.persistence.EntityNotFoundException; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@AutoConfigureTestDatabase +@TestPropertySource(locations = {"/test.properties", "/unit-test.properties"}) +@RunWith(SpringRunner.class) +@WebMvcTest(RestfulPetController.class) +public class RestfulPetControllerTests { + @Autowired + private MockMvc mockMvc; + + @Mock + private Pet petMock; + + @MockBean + private PetRepository petRepository; + + private Pet createInvalidPet() { + return new Pet(); + } + + private Pet createValidPet() { + return new Pet() {{ + setId(1); + setName("HelloKitty"); + setOwner(new Owner() {{ + setId(1); + }}); + setType(new PetType() {{ + setId(1); + }}); + }}; + } + + @Test + public void shouldReturnAllPetsList() throws Exception { + List petList = Collections.singletonList(createValidPet()); + when(petRepository.getAll()).thenReturn(petList); + + mockMvc.perform(get("/api/pets").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(content().json(TestUtil.objectToJsonString(petList, PetJsonView.class))); + + verify(petRepository).getAll(); + verifyNoMoreInteractions(petRepository); + } + + @Test + public void shouldReturnPetWhenPetExists() throws Exception { + Pet pet = createValidPet(); + when(petRepository.getById(1)).thenReturn(pet); + + System.out.printf(TestUtil.objectToJsonString(pet)); + + mockMvc.perform(get("/api/pets/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(content().json(TestUtil.objectToJsonString(pet, PetJsonView.class))); + } + + @Test + public void shouldReturnNotFoundWhenPetNotExists() throws Exception { + when(petRepository.getById(1)).thenReturn(null); + + mockMvc.perform(get("/api/pets/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + + verify(petRepository).getById(1); + verifyNoMoreInteractions(petRepository); + } + + @Test + public void shouldCreatePetWhenPetIsValid() throws Exception { + Pet pet = createValidPet(); + when(petRepository.insert(pet)).thenReturn(1); + + MockHttpServletRequestBuilder req = post("/api/pets") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(pet)); + + mockMvc.perform(req) + .andExpect(status().isCreated()); + } + + @Test + public void shouldFailToCreateVisitWhenPetIsInvalid() throws Exception { + MockHttpServletRequestBuilder req = post("/api/pets") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createInvalidPet())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + + verifyZeroInteractions(petRepository); + } + + @Test + public void shouldUpdatePetWhenPetIsValid() throws Exception { + MockHttpServletRequestBuilder req = post("/api/pets/1") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createValidPet())); + + mockMvc.perform(req) + .andExpect(status().isNoContent()); + } + + @Test + public void shouldFailToUpdatePetWhenPetIsInvalid() throws Exception { + MockHttpServletRequestBuilder req = post("/api/pets/1") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createInvalidPet())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + } + + + @Test + public void shouldFailToUpdatePetWhenPetNotExist() throws Exception { + doThrow(EntityNotFoundException.class).when(petRepository).update(any(Pet.class)); + MockHttpServletRequestBuilder req = post("/api/pets/1") + .accept(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createValidPet())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + } + + @Test + public void shouldDeletePetWhenPetExists() throws Exception { + mockMvc.perform(delete("/api/pets/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + verify(petRepository).deleteById(1); + verifyNoMoreInteractions(petRepository); + } + + @Test + public void shouldFailToDeletePetWhenPetNotExist() throws Exception { + doThrow(EntityNotFoundException.class).when(petRepository).deleteById(1); + + mockMvc.perform(delete("/api/pets/1").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + + verify(petRepository).deleteById(1); + verifyNoMoreInteractions(petRepository); + } +} diff --git a/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java new file mode 100644 index 0000000..29117d0 --- /dev/null +++ b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java @@ -0,0 +1,63 @@ +package tk.puncha.unit.restfulControllers; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import tk.puncha.TestUtil; +import tk.puncha.models.PetType; +import tk.puncha.repositories.PetTypeRepository; +import tk.puncha.restfulControllers.RestfulPetTypeController; + +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@AutoConfigureTestDatabase +@TestPropertySource(locations = {"/test.properties", "/unit-test.properties"}) +@RunWith(SpringRunner.class) +@WebMvcTest(RestfulPetTypeController.class) +public class RestfulPetTypeControllerTests { + @Autowired + private MockMvc mockMvc; + + @MockBean + private PetTypeRepository petTypeRepository; + + @Test + public void shouldGetAllPetTypes() throws Exception { + List petTypeList = createSamplePetTypeList(); + + when(petTypeRepository.getAll()).thenReturn(petTypeList); + + MockHttpServletRequestBuilder req = get("/api/petTypes") + .accept(MediaType.APPLICATION_JSON); + + mockMvc.perform(req) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + .andExpect(content().json(TestUtil.objectToJsonString(petTypeList))); + + verify(petTypeRepository).getAll(); + verifyNoMoreInteractions(petTypeRepository); + } + + private List createSamplePetTypeList() { + return Collections.singletonList(new PetType() {{ + setId(1); + setName("Tiger"); + }}); + } +} From 58c33477902b358849121ab4c811d0eff299e767 Mon Sep 17 00:00:00 2001 From: PunCha Date: Tue, 23 Aug 2016 00:52:26 +0800 Subject: [PATCH 11/29] Refactor: tests --- src/test/java/tk/puncha/TestUtil.java | 43 ++++++++++++++++--- .../tk/puncha/unit/models/VisitTests.java | 3 +- .../RestfulOwnerControllerTests.java | 29 ++++--------- .../RestfulPetControllerTests.java | 34 +++------------ .../RestfulPetTypeControllerTests.java | 12 ++---- 5 files changed, 56 insertions(+), 65 deletions(-) diff --git a/src/test/java/tk/puncha/TestUtil.java b/src/test/java/tk/puncha/TestUtil.java index dc66504..8294884 100644 --- a/src/test/java/tk/puncha/TestUtil.java +++ b/src/test/java/tk/puncha/TestUtil.java @@ -7,6 +7,9 @@ import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import tk.puncha.models.Owner; +import tk.puncha.models.Pet; +import tk.puncha.models.PetType; import javax.validation.ConstraintViolation; import javax.validation.Validator; @@ -40,13 +43,6 @@ public static void assertViolation( assertEquals(message, violation.getMessage()); } - - public static byte[] objectToJsonBytes(Object object) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - return mapper.writeValueAsBytes(object); - } - public static String objectToJsonString(Object object) throws JsonProcessingException { return objectToJsonString(object, null); } @@ -60,4 +56,37 @@ public static String objectToJsonString(Object object, Class viewClass) throws J } return mapper.writeValueAsString(object); } + + public static Owner createInvalidOwner() { + return new Owner(); + } + + public static Owner createValidOwner() { + return new Owner() {{ + setId(1); + setFirstName("PunCha"); + setLastName("Feng"); + setAddress("Shanghai"); + }}; + } + + public static Pet createInvalidPet() { + return new Pet(); + } + + public static Pet createValidPet() { + return new Pet() {{ + setId(1); + setName("HelloKitty"); + setOwner(createValidOwner()); + setType(createValidPetType()); + }}; + } + + public static PetType createValidPetType() { + return new PetType() {{ + setId(1); + setName("Tiger"); + }}; + } } diff --git a/src/test/java/tk/puncha/unit/models/VisitTests.java b/src/test/java/tk/puncha/unit/models/VisitTests.java index ec2522d..91758b9 100644 --- a/src/test/java/tk/puncha/unit/models/VisitTests.java +++ b/src/test/java/tk/puncha/unit/models/VisitTests.java @@ -11,6 +11,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; public class VisitTests { @@ -37,7 +38,7 @@ public void shouldDefaultVisitNotValidate() throws Exception { @Test public void shouldVisitValidate() throws Exception { - visit.setVisitDate(new Date(2016,6,6)); + visit.setVisitDate(mock(Date.class)); Set> violations = TestUtil.createValidator().validate(visit); assertEquals(0, violations.size()); } diff --git a/src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java b/src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java index 74b29e5..c38116e 100644 --- a/src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java +++ b/src/test/java/tk/puncha/unit/restfulControllers/RestfulOwnerControllerTests.java @@ -46,19 +46,6 @@ public class RestfulOwnerControllerTests { @MockBean private OwnerRepository ownerRepository; - private Owner createInvalidOwner() { - return new Owner(); - } - - private Owner createValidOwner() { - return new Owner() {{ - setId(1); - setFirstName("PunCha"); - setLastName("Feng"); - setAddress("Shanghai"); - }}; - } - @Before public void makeValidatorSupportsAnyType() { when(ownerValidator.supports(any())).thenReturn(true); @@ -66,7 +53,7 @@ public void makeValidatorSupportsAnyType() { @Test public void shouldReturnAllOwnersList() throws Exception { - List ownerList = Collections.singletonList(createValidOwner()); + List ownerList = Collections.singletonList(TestUtil.createValidOwner()); when(ownerRepository.getAll()).thenReturn(ownerList); mockMvc.perform(get("/api/owners").accept(MediaType.APPLICATION_JSON)) @@ -80,7 +67,7 @@ public void shouldReturnAllOwnersList() throws Exception { @Test public void shouldReturnOwnersListFilterByFirstName() throws Exception { - List ownerList = Collections.singletonList(createValidOwner()); + List ownerList = Collections.singletonList(TestUtil.createValidOwner()); when(ownerRepository.findByFirstName("puncha")).thenReturn(ownerList); mockMvc.perform(get("/api/owners?firstName=puncha").accept(MediaType.APPLICATION_JSON)) @@ -94,7 +81,7 @@ public void shouldReturnOwnersListFilterByFirstName() throws Exception { @Test public void shouldReturnOwnerWhenOwnerExists() throws Exception { - Owner owner = createValidOwner(); + Owner owner = TestUtil.createValidOwner(); when(ownerRepository.getByIdWithPets(1)).thenReturn(owner); System.out.printf(TestUtil.objectToJsonString(owner)); @@ -116,7 +103,7 @@ public void shouldReturnNotFoundWhenOwnerNotExists() throws Exception { @Test public void shouldCreateOwnerWhenOwnerIsValid() throws Exception { - Owner owner = createValidOwner(); + Owner owner = TestUtil.createValidOwner(); when(ownerRepository.insert(owner)).thenReturn(1); MockHttpServletRequestBuilder req = post("/api/owners") @@ -133,7 +120,7 @@ public void shouldFailToCreateVisitWhenOwnerIsInvalid() throws Exception { MockHttpServletRequestBuilder req = post("/api/owners") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createInvalidOwner())); + .content(TestUtil.objectToJsonString(TestUtil.createInvalidOwner())); mockMvc.perform(req) .andExpect(status().isBadRequest()); @@ -146,7 +133,7 @@ public void shouldUpdateOwnerWhenOwnerIsValid() throws Exception { MockHttpServletRequestBuilder req = post("/api/owners/1") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createValidOwner())); + .content(TestUtil.objectToJsonString(TestUtil.createValidOwner())); mockMvc.perform(req) .andExpect(status().isNoContent()); @@ -157,7 +144,7 @@ public void shouldFailToUpdateOwnerWhenOwnerIsInvalid() throws Exception { MockHttpServletRequestBuilder req = post("/api/owners/1") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createInvalidOwner())); + .content(TestUtil.objectToJsonString(TestUtil.createInvalidOwner())); mockMvc.perform(req) .andExpect(status().isBadRequest()); @@ -169,7 +156,7 @@ public void shouldFailToUpdateOwnerWhenOwnerNotExist() throws Exception { doThrow(EntityNotFoundException.class).when(ownerRepository).update(any(Owner.class)); MockHttpServletRequestBuilder req = post("/api/owners/1") .accept(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createValidOwner())); + .content(TestUtil.objectToJsonString(TestUtil.createValidOwner())); mockMvc.perform(req) .andExpect(status().isBadRequest()); diff --git a/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java index 823d0dd..f63f5a7 100644 --- a/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java +++ b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetControllerTests.java @@ -13,9 +13,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import tk.puncha.TestUtil; -import tk.puncha.models.Owner; import tk.puncha.models.Pet; -import tk.puncha.models.PetType; import tk.puncha.repositories.PetRepository; import tk.puncha.restfulControllers.RestfulPetController; import tk.puncha.views.json.view.PetJsonView; @@ -44,26 +42,9 @@ public class RestfulPetControllerTests { @MockBean private PetRepository petRepository; - private Pet createInvalidPet() { - return new Pet(); - } - - private Pet createValidPet() { - return new Pet() {{ - setId(1); - setName("HelloKitty"); - setOwner(new Owner() {{ - setId(1); - }}); - setType(new PetType() {{ - setId(1); - }}); - }}; - } - @Test public void shouldReturnAllPetsList() throws Exception { - List petList = Collections.singletonList(createValidPet()); + List petList = Collections.singletonList(TestUtil.createValidPet()); when(petRepository.getAll()).thenReturn(petList); mockMvc.perform(get("/api/pets").accept(MediaType.APPLICATION_JSON)) @@ -77,7 +58,7 @@ public void shouldReturnAllPetsList() throws Exception { @Test public void shouldReturnPetWhenPetExists() throws Exception { - Pet pet = createValidPet(); + Pet pet = TestUtil.createValidPet(); when(petRepository.getById(1)).thenReturn(pet); System.out.printf(TestUtil.objectToJsonString(pet)); @@ -101,7 +82,7 @@ public void shouldReturnNotFoundWhenPetNotExists() throws Exception { @Test public void shouldCreatePetWhenPetIsValid() throws Exception { - Pet pet = createValidPet(); + Pet pet = TestUtil.createValidPet(); when(petRepository.insert(pet)).thenReturn(1); MockHttpServletRequestBuilder req = post("/api/pets") @@ -118,7 +99,7 @@ public void shouldFailToCreateVisitWhenPetIsInvalid() throws Exception { MockHttpServletRequestBuilder req = post("/api/pets") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createInvalidPet())); + .content(TestUtil.objectToJsonString(TestUtil.createInvalidPet())); mockMvc.perform(req) .andExpect(status().isBadRequest()); @@ -131,7 +112,7 @@ public void shouldUpdatePetWhenPetIsValid() throws Exception { MockHttpServletRequestBuilder req = post("/api/pets/1") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createValidPet())); + .content(TestUtil.objectToJsonString(TestUtil.createValidPet())); mockMvc.perform(req) .andExpect(status().isNoContent()); @@ -142,19 +123,18 @@ public void shouldFailToUpdatePetWhenPetIsInvalid() throws Exception { MockHttpServletRequestBuilder req = post("/api/pets/1") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createInvalidPet())); + .content(TestUtil.objectToJsonString(TestUtil.createInvalidPet())); mockMvc.perform(req) .andExpect(status().isBadRequest()); } - @Test public void shouldFailToUpdatePetWhenPetNotExist() throws Exception { doThrow(EntityNotFoundException.class).when(petRepository).update(any(Pet.class)); MockHttpServletRequestBuilder req = post("/api/pets/1") .accept(MediaType.APPLICATION_JSON) - .content(TestUtil.objectToJsonString(createValidPet())); + .content(TestUtil.objectToJsonString(TestUtil.createValidPet())); mockMvc.perform(req) .andExpect(status().isBadRequest()); diff --git a/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java index 29117d0..7773707 100644 --- a/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java +++ b/src/test/java/tk/puncha/unit/restfulControllers/RestfulPetTypeControllerTests.java @@ -38,9 +38,9 @@ public class RestfulPetTypeControllerTests { @Test public void shouldGetAllPetTypes() throws Exception { - List petTypeList = createSamplePetTypeList(); + List petTypes = Collections.singletonList(TestUtil.createValidPetType()); - when(petTypeRepository.getAll()).thenReturn(petTypeList); + when(petTypeRepository.getAll()).thenReturn(petTypes); MockHttpServletRequestBuilder req = get("/api/petTypes") .accept(MediaType.APPLICATION_JSON); @@ -48,16 +48,10 @@ public void shouldGetAllPetTypes() throws Exception { mockMvc.perform(req) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(content().json(TestUtil.objectToJsonString(petTypeList))); + .andExpect(content().json(TestUtil.objectToJsonString(petTypes))); verify(petTypeRepository).getAll(); verifyNoMoreInteractions(petTypeRepository); } - private List createSamplePetTypeList() { - return Collections.singletonList(new PetType() {{ - setId(1); - setName("Tiger"); - }}); - } } From f81f0eab077a72c71cc57d37085d11d693201c32 Mon Sep 17 00:00:00 2001 From: PunCha Date: Tue, 23 Aug 2016 01:01:42 +0800 Subject: [PATCH 12/29] Disable all the integration tests --- .../java/tk/puncha/integration/webapp/ControllerTests.java | 2 ++ .../tk/puncha/integration/webapp/ErrorControllerTests.java | 3 +++ .../java/tk/puncha/integration/webapp/HomeControllerTests.java | 3 +++ .../tk/puncha/integration/webapp/OwnerControllerTests.java | 2 ++ .../tk/puncha/integration/webapp/PetAndVisitCreationTests.java | 2 ++ .../java/tk/puncha/integration/webapp/PetControllerTests.java | 2 ++ 6 files changed, 14 insertions(+) diff --git a/src/test/java/tk/puncha/integration/webapp/ControllerTests.java b/src/test/java/tk/puncha/integration/webapp/ControllerTests.java index 6149d48..bc282b5 100644 --- a/src/test/java/tk/puncha/integration/webapp/ControllerTests.java +++ b/src/test/java/tk/puncha/integration/webapp/ControllerTests.java @@ -2,6 +2,7 @@ import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.*; +import org.junit.Ignore; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; @@ -15,6 +16,7 @@ @AutoConfigureTestDatabase @TestPropertySource(locations = "classpath:test.properties") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Ignore abstract class ControllerTests { @Value("${local.server.port}") diff --git a/src/test/java/tk/puncha/integration/webapp/ErrorControllerTests.java b/src/test/java/tk/puncha/integration/webapp/ErrorControllerTests.java index b558b2b..578d09e 100644 --- a/src/test/java/tk/puncha/integration/webapp/ErrorControllerTests.java +++ b/src/test/java/tk/puncha/integration/webapp/ErrorControllerTests.java @@ -1,5 +1,8 @@ package tk.puncha.integration.webapp; +import org.junit.Ignore; + // TODO: Implement the test +@Ignore public class ErrorControllerTests { } diff --git a/src/test/java/tk/puncha/integration/webapp/HomeControllerTests.java b/src/test/java/tk/puncha/integration/webapp/HomeControllerTests.java index 33aaa66..7a56757 100644 --- a/src/test/java/tk/puncha/integration/webapp/HomeControllerTests.java +++ b/src/test/java/tk/puncha/integration/webapp/HomeControllerTests.java @@ -1,5 +1,8 @@ package tk.puncha.integration.webapp; +import org.junit.Ignore; + // TODO: Implement the test +@Ignore public class HomeControllerTests { } diff --git a/src/test/java/tk/puncha/integration/webapp/OwnerControllerTests.java b/src/test/java/tk/puncha/integration/webapp/OwnerControllerTests.java index f5431f9..250c7f8 100644 --- a/src/test/java/tk/puncha/integration/webapp/OwnerControllerTests.java +++ b/src/test/java/tk/puncha/integration/webapp/OwnerControllerTests.java @@ -3,6 +3,7 @@ import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; @@ -13,6 +14,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +@Ignore public class OwnerControllerTests extends ControllerTests { @Configuration @EnableAutoConfiguration diff --git a/src/test/java/tk/puncha/integration/webapp/PetAndVisitCreationTests.java b/src/test/java/tk/puncha/integration/webapp/PetAndVisitCreationTests.java index 130d0ea..40a50c0 100644 --- a/src/test/java/tk/puncha/integration/webapp/PetAndVisitCreationTests.java +++ b/src/test/java/tk/puncha/integration/webapp/PetAndVisitCreationTests.java @@ -2,6 +2,7 @@ import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; @@ -9,6 +10,7 @@ import static org.junit.Assert.assertTrue; +@Ignore public class PetAndVisitCreationTests extends ControllerTests { @Configuration diff --git a/src/test/java/tk/puncha/integration/webapp/PetControllerTests.java b/src/test/java/tk/puncha/integration/webapp/PetControllerTests.java index 4f871ed..d4ba316 100644 --- a/src/test/java/tk/puncha/integration/webapp/PetControllerTests.java +++ b/src/test/java/tk/puncha/integration/webapp/PetControllerTests.java @@ -3,6 +3,7 @@ import com.gargoylesoftware.htmlunit.html.DomAttr; import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; @@ -13,6 +14,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +@Ignore public class PetControllerTests extends ControllerTests { @Configuration From 12fd871c230f47b86783149aaa103b8036d094b7 Mon Sep 17 00:00:00 2001 From: PunCha Date: Tue, 23 Aug 2016 01:49:40 +0800 Subject: [PATCH 13/29] Add unit test for MyErrorViewResolver --- .../tk/puncha/configuration/WebConfig.java | 2 +- .../MyErrorViewResolver.java | 2 +- .../MyErrorViewResolverTests.java | 40 +++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) rename src/main/java/tk/puncha/{handlers => viewResolvers}/MyErrorViewResolver.java (94%) create mode 100644 src/test/java/tk/puncha/viewResolvers/MyErrorViewResolverTests.java diff --git a/src/main/java/tk/puncha/configuration/WebConfig.java b/src/main/java/tk/puncha/configuration/WebConfig.java index 16ca999..4384c81 100644 --- a/src/main/java/tk/puncha/configuration/WebConfig.java +++ b/src/main/java/tk/puncha/configuration/WebConfig.java @@ -22,7 +22,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; import org.springframework.web.servlet.view.XmlViewResolver; -import tk.puncha.handlers.MyErrorViewResolver; +import tk.puncha.viewResolvers.MyErrorViewResolver; import tk.puncha.viewResolvers.AtomFeedViewResolver; import tk.puncha.viewResolvers.ExcelViewResolver; import tk.puncha.viewResolvers.JsonViewResolver; diff --git a/src/main/java/tk/puncha/handlers/MyErrorViewResolver.java b/src/main/java/tk/puncha/viewResolvers/MyErrorViewResolver.java similarity index 94% rename from src/main/java/tk/puncha/handlers/MyErrorViewResolver.java rename to src/main/java/tk/puncha/viewResolvers/MyErrorViewResolver.java index b881dfc..11d531d 100644 --- a/src/main/java/tk/puncha/handlers/MyErrorViewResolver.java +++ b/src/main/java/tk/puncha/viewResolvers/MyErrorViewResolver.java @@ -1,4 +1,4 @@ -package tk.puncha.handlers; +package tk.puncha.viewResolvers; import org.springframework.boot.autoconfigure.web.ErrorViewResolver; import org.springframework.http.HttpStatus; diff --git a/src/test/java/tk/puncha/viewResolvers/MyErrorViewResolverTests.java b/src/test/java/tk/puncha/viewResolvers/MyErrorViewResolverTests.java new file mode 100644 index 0000000..bfb68cb --- /dev/null +++ b/src/test/java/tk/puncha/viewResolvers/MyErrorViewResolverTests.java @@ -0,0 +1,40 @@ +package tk.puncha.viewResolvers; + + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.servlet.ModelAndView; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +// Hack: I cannot make MyErrorViewResolver work when accessing an invalid path, +// so I have to test its method here... How can I really test it? +public class MyErrorViewResolverTests { + private MyErrorViewResolver resolver; + + @Before + public void initMyErrorViewResolver() { + resolver = new MyErrorViewResolver(); + } + + @Test + public void shouldRedirectTo404PageWhenStatusCodeIs404() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HashMap model = new HashMap<>(); + ModelAndView modelAndView = resolver.resolveErrorView(request, HttpStatus.NOT_FOUND, model); + assertEquals(modelAndView.getViewName(), "forward:/resources/error/404.html"); + } + + @Test + public void shouldReturnNullWhenStatusCodeIsAllButNot404() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HashMap model = new HashMap<>(); + ModelAndView modelAndView = resolver.resolveErrorView(request, HttpStatus.SERVICE_UNAVAILABLE, model); + assertNull(modelAndView); + } +} From c868dcd3eb150d81117d2f28386095cab880940e Mon Sep 17 00:00:00 2001 From: PunCha Date: Fri, 16 Sep 2016 11:53:28 +0800 Subject: [PATCH 14/29] Add unit test for Restful Visit Controller --- .../RestfulVisitControllerTests.java | 152 ++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 src/test/java/tk/puncha/unit/restfulControllers/RestfulVisitControllerTests.java diff --git a/src/test/java/tk/puncha/unit/restfulControllers/RestfulVisitControllerTests.java b/src/test/java/tk/puncha/unit/restfulControllers/RestfulVisitControllerTests.java new file mode 100644 index 0000000..b2eaeea --- /dev/null +++ b/src/test/java/tk/puncha/unit/restfulControllers/RestfulVisitControllerTests.java @@ -0,0 +1,152 @@ +package tk.puncha.unit.restfulControllers; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase; +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import tk.puncha.TestUtil; +import tk.puncha.models.Pet; +import tk.puncha.models.Visit; +import tk.puncha.repositories.PetRepository; +import tk.puncha.repositories.VisitRepository; +import tk.puncha.restfulControllers.RestfulVisitController; + +import javax.persistence.EntityNotFoundException; +import java.sql.Date; + +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@AutoConfigureTestDatabase +@TestPropertySource(locations = {"/test.properties", "/unit-test.properties"}) +@RunWith(SpringRunner.class) +@WebMvcTest(RestfulVisitController.class) +public class RestfulVisitControllerTests { + @Autowired + private MockMvc mockMvc; + + @Mock + private Date dateMock; + @Mock + private Pet petMock; + + @MockBean + private PetRepository petRepository; + @MockBean + private VisitRepository visitRepository; + + private Visit createInvalidVisit() { + return new Visit(); + } + + private Visit createValidVisit() { + Visit visit = createInvalidVisit(); + visit.setVisitDate(dateMock); + return visit; + } + + + @Test + public void shouldCreateVisitWhenVisitIsValid() throws Exception { + when(petRepository.getById(1)).thenReturn(petMock); + + MockHttpServletRequestBuilder req = post("/api/pets/1/visits") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createValidVisit())); + + mockMvc.perform(req) + .andExpect(status().isCreated()); + } + + @Test + public void shouldFailToCreateVisitWhenVisitIsInvalid() throws Exception { + when(petRepository.getById(1)).thenReturn(petMock); + + MockHttpServletRequestBuilder req = post("/api/pets/1/visits") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createInvalidVisit())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); + + verify(petRepository).getById(1); + verifyNoMoreInteractions(petRepository, visitRepository); + } + + @Test + public void shouldFailToCreateVisitWhenPetNotExists() throws Exception { + when(petRepository.getById(1)).thenReturn(null); + + MockHttpServletRequestBuilder req = post("/api/pets/1/visits") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.objectToJsonString(createValidVisit())); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + + verify(petRepository).getById(1); + verifyNoMoreInteractions(petRepository, visitRepository); + } + + @Test + public void shouldDeleteVisit() throws Exception { + when(petRepository.getById(1)).thenReturn(petMock); + + MockHttpServletRequestBuilder req = delete("/api/pets/1/visits/2") + .accept(MediaType.APPLICATION_JSON); + + mockMvc.perform(req) + .andExpect(status().isNoContent()); + + verify(petRepository).getById(1); + verify(visitRepository).deleteById(2); + verifyNoMoreInteractions(petRepository, visitRepository); + } + + @Test + public void shouldFailToDeleteVisitWhenVisitDoesNotExist() throws Exception { + when(petRepository.getById(1)).thenReturn(petMock); + doThrow(EntityNotFoundException.class).when(visitRepository).deleteById(2); + + MockHttpServletRequestBuilder req = delete("/api/pets/1/visits/2") + .accept(MediaType.APPLICATION_JSON); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + + verify(petRepository).getById(1); + verify(visitRepository).deleteById(2); + verifyNoMoreInteractions(petRepository, visitRepository); + } + + @Test + public void shouldFailToDeleteVisitWhenPetDoesNotExist() throws Exception { + when(petRepository.getById(1)).thenReturn(null); + + MockHttpServletRequestBuilder req = delete("/api/pets/1/visits/2") + .accept(MediaType.APPLICATION_JSON); + + mockMvc.perform(req) + .andExpect(status().isBadRequest()); + + verify(petRepository).getById(1); + verifyNoMoreInteractions(petRepository, visitRepository); + } + +} From 9e919a1ff261353ab2fe761ea0ec2c9ea83cfa6b Mon Sep 17 00:00:00 2001 From: PunCha Date: Thu, 8 Sep 2016 01:00:33 +0800 Subject: [PATCH 15/29] Create skeleton of Angular2 app --- .../tk/puncha/configuration/WebConfig.java | 1 + .../resources/ng2/app/app.component.html | 3 ++ .../webapp/resources/ng2/app/app.component.ts | 10 ++++ .../webapp/resources/ng2/app/app.module.ts | 15 ++++++ .../resources/ng2/app/footer.component.html | 4 ++ .../resources/ng2/app/footer.component.ts | 9 ++++ src/main/webapp/resources/ng2/app/main.ts | 3 ++ .../resources/ng2/app/nav.component.html | 26 ++++++++++ .../webapp/resources/ng2/app/nav.component.ts | 10 ++++ .../resources/ng2/app/welcome.component.html | 3 ++ .../resources/ng2/app/welcome.component.ts | 9 ++++ src/main/webapp/resources/ng2/index.html | 30 +++++++++++ src/main/webapp/resources/ng2/module.d.ts | 3 ++ src/main/webapp/resources/ng2/styles.css | 0 .../webapp/resources/ng2/systemjs.config.js | 52 +++++++++++++++++++ src/main/webapp/resources/ng2/tsconfig.json | 12 +++++ src/main/webapp/resources/ng2/typings.json | 7 +++ 17 files changed, 197 insertions(+) create mode 100644 src/main/webapp/resources/ng2/app/app.component.html create mode 100644 src/main/webapp/resources/ng2/app/app.component.ts create mode 100644 src/main/webapp/resources/ng2/app/app.module.ts create mode 100644 src/main/webapp/resources/ng2/app/footer.component.html create mode 100644 src/main/webapp/resources/ng2/app/footer.component.ts create mode 100644 src/main/webapp/resources/ng2/app/main.ts create mode 100644 src/main/webapp/resources/ng2/app/nav.component.html create mode 100644 src/main/webapp/resources/ng2/app/nav.component.ts create mode 100644 src/main/webapp/resources/ng2/app/welcome.component.html create mode 100644 src/main/webapp/resources/ng2/app/welcome.component.ts create mode 100644 src/main/webapp/resources/ng2/index.html create mode 100644 src/main/webapp/resources/ng2/module.d.ts create mode 100644 src/main/webapp/resources/ng2/styles.css create mode 100644 src/main/webapp/resources/ng2/systemjs.config.js create mode 100644 src/main/webapp/resources/ng2/tsconfig.json create mode 100644 src/main/webapp/resources/ng2/typings.json diff --git a/src/main/java/tk/puncha/configuration/WebConfig.java b/src/main/java/tk/puncha/configuration/WebConfig.java index 4384c81..5700c51 100644 --- a/src/main/java/tk/puncha/configuration/WebConfig.java +++ b/src/main/java/tk/puncha/configuration/WebConfig.java @@ -39,6 +39,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/ng1/**").addResourceLocations("/resources/ng1/"); + registry.addResourceHandler("/ng2/**").addResourceLocations("/resources/ng2/"); } @Override diff --git a/src/main/webapp/resources/ng2/app/app.component.html b/src/main/webapp/resources/ng2/app/app.component.html new file mode 100644 index 0000000..5f89378 --- /dev/null +++ b/src/main/webapp/resources/ng2/app/app.component.html @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/app.component.ts b/src/main/webapp/resources/ng2/app/app.component.ts new file mode 100644 index 0000000..eb0e4fc --- /dev/null +++ b/src/main/webapp/resources/ng2/app/app.component.ts @@ -0,0 +1,10 @@ +import {Component} from "@angular/core"; + +@Component({ + moduleId: module.id, + selector: 'ptc-app', + templateUrl: 'app.component.html', +}) +export class AppComponent { + +} diff --git a/src/main/webapp/resources/ng2/app/app.module.ts b/src/main/webapp/resources/ng2/app/app.module.ts new file mode 100644 index 0000000..5f02d1c --- /dev/null +++ b/src/main/webapp/resources/ng2/app/app.module.ts @@ -0,0 +1,15 @@ +import {NgModule} from "@angular/core"; +import {BrowserModule} from "@angular/platform-browser"; +import {NgbModule} from "@ng-bootstrap/ng-bootstrap"; +import {AppComponent} from "./app.component"; +import {WelcomeComponent} from "./welcome.component"; +import {NavComponent} from "./nav.component"; +import {FooterComponent} from "./footer.component"; + +@NgModule({ + imports: [BrowserModule, NgbModule], + declarations: [AppComponent, WelcomeComponent, NavComponent, FooterComponent], + bootstrap: [AppComponent] +}) +export class AppModule { +} \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/footer.component.html b/src/main/webapp/resources/ng2/app/footer.component.html new file mode 100644 index 0000000..95f98ef --- /dev/null +++ b/src/main/webapp/resources/ng2/app/footer.component.html @@ -0,0 +1,4 @@ +
+
+ +
diff --git a/src/main/webapp/resources/ng2/app/footer.component.ts b/src/main/webapp/resources/ng2/app/footer.component.ts new file mode 100644 index 0000000..c8c32ce --- /dev/null +++ b/src/main/webapp/resources/ng2/app/footer.component.ts @@ -0,0 +1,9 @@ +import {Component} from "@angular/core"; +@Component({ + moduleId: module.id, + selector: 'ptc-footer', + templateUrl: 'footer.component.html' +}) +export class FooterComponent{ + +} \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/main.ts b/src/main/webapp/resources/ng2/app/main.ts new file mode 100644 index 0000000..bf1b269 --- /dev/null +++ b/src/main/webapp/resources/ng2/app/main.ts @@ -0,0 +1,3 @@ +import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; +import {AppModule} from './app.module'; +platformBrowserDynamic().bootstrapModule(AppModule); \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/nav.component.html b/src/main/webapp/resources/ng2/app/nav.component.html new file mode 100644 index 0000000..1b791ef --- /dev/null +++ b/src/main/webapp/resources/ng2/app/nav.component.html @@ -0,0 +1,26 @@ + \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/nav.component.ts b/src/main/webapp/resources/ng2/app/nav.component.ts new file mode 100644 index 0000000..bca6a2a --- /dev/null +++ b/src/main/webapp/resources/ng2/app/nav.component.ts @@ -0,0 +1,10 @@ +import {Component} from "@angular/core"; + +@Component({ + moduleId: module.id, + selector: 'ptc-nav', + templateUrl: 'nav.component.html' +}) +export class NavComponent { + +} \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/welcome.component.html b/src/main/webapp/resources/ng2/app/welcome.component.html new file mode 100644 index 0000000..dba2973 --- /dev/null +++ b/src/main/webapp/resources/ng2/app/welcome.component.html @@ -0,0 +1,3 @@ +
+ +
\ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/welcome.component.ts b/src/main/webapp/resources/ng2/app/welcome.component.ts new file mode 100644 index 0000000..4f0d35a --- /dev/null +++ b/src/main/webapp/resources/ng2/app/welcome.component.ts @@ -0,0 +1,9 @@ +import {Component} from "@angular/core"; +@Component({ + moduleId: module.id, + selector: 'ptc-welcome', + templateUrl: 'welcome.component.html' +}) +export class WelcomeComponent { + +} \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/index.html b/src/main/webapp/resources/ng2/index.html new file mode 100644 index 0000000..c0626fa --- /dev/null +++ b/src/main/webapp/resources/ng2/index.html @@ -0,0 +1,30 @@ + + + Spring PetClinic + + + + + + + + + + + + + + + + + + + + +Loading... + + \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/module.d.ts b/src/main/webapp/resources/ng2/module.d.ts new file mode 100644 index 0000000..2886663 --- /dev/null +++ b/src/main/webapp/resources/ng2/module.d.ts @@ -0,0 +1,3 @@ +// This is a hack to cheat JetBrains IDE. See: +// http://stackoverflow.com/questions/36700693/typescript-error-in-angular2-code-cannot-find-name-module +declare var module: {id: string}; \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/styles.css b/src/main/webapp/resources/ng2/styles.css new file mode 100644 index 0000000..e69de29 diff --git a/src/main/webapp/resources/ng2/systemjs.config.js b/src/main/webapp/resources/ng2/systemjs.config.js new file mode 100644 index 0000000..065a694 --- /dev/null +++ b/src/main/webapp/resources/ng2/systemjs.config.js @@ -0,0 +1,52 @@ +/** + * System configuration for Angular 2 samples + * Adjust as necessary for your application needs. + */ +(function(global) { + // map tells the System loader where to look for things + var map = { + 'app': 'app', // 'dist', + '@angular': 'node_modules/@angular', + '@ng-bootstrap': 'node_modules/@ng-bootstrap', + 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', + 'rxjs': 'node_modules/rxjs' + }; + // packages tells the System loader how to load when no filename and/or no extension + var packages = { + 'app': {main: 'main.js', defaultExtension: 'js'}, + 'rxjs': {defaultExtension: 'js'}, + 'angular2-in-memory-web-api': {main: 'index.js', defaultExtension: 'js'}, + '@ng-bootstrap/ng-bootstrap': {main: 'index.js', defaultExtension: 'js'} + }; + var ngPackageNames = [ + 'common', + 'compiler', + 'core', + 'forms', + 'http', + 'platform-browser', + 'platform-browser-dynamic', + 'router', + 'router-deprecated', + 'upgrade', + ]; + // Individual files (~300 requests): + function packIndex(pkgName) { + packages['@angular/' + pkgName] = {main: 'index.js', defaultExtension: 'js'}; + } + + // Bundled (~40 requests): + function packUmd(pkgName) { + packages['@angular/' + pkgName] = {main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js'}; + } + + // Most environments should use UMD; some (Karma) need the individual index files + var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; + // Add package entries for angular packages + ngPackageNames.forEach(setPackageConfig); + var config = { + map: map, + packages: packages + }; + System.config(config); +})(this); \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/tsconfig.json b/src/main/webapp/resources/ng2/tsconfig.json new file mode 100644 index 0000000..6612f8e --- /dev/null +++ b/src/main/webapp/resources/ng2/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "moduleResolution": "node", + "sourceMap": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "removeComments": false, + "noImplicitAny": false + } +} \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/typings.json b/src/main/webapp/resources/ng2/typings.json new file mode 100644 index 0000000..fa8db6b --- /dev/null +++ b/src/main/webapp/resources/ng2/typings.json @@ -0,0 +1,7 @@ +{ + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160602141332", + "jasmine": "registry:dt/jasmine#2.2.0+20160621224255", + "node": "registry:dt/node#6.0.0+20160608110640" + } +} \ No newline at end of file From b4a9dd0d4a08c5ff94616c3f75bf276be343865e Mon Sep 17 00:00:00 2001 From: PunCha Date: Fri, 9 Sep 2016 00:26:38 +0800 Subject: [PATCH 16/29] Add Owners page --- .../resources/ng2/app/app.component.html | 2 +- .../webapp/resources/ng2/app/app.module.ts | 23 +++++++++++-- .../webapp/resources/ng2/app/app.routing.ts | 16 +++++++++ .../resources/ng2/app/nav.component.html | 8 +++-- .../ng2/app/owner-list.component.html | 28 ++++++++++++++++ .../resources/ng2/app/owner-list.component.ts | 33 +++++++++++++++++++ .../webapp/resources/ng2/app/owner.service.ts | 19 +++++++++++ .../resources/ng2/app/owners.component.html | 17 ++++++++++ .../resources/ng2/app/owners.component.ts | 18 ++++++++++ .../resources/ng2/app/pet-list.component.ts | 9 +++++ 10 files changed, 167 insertions(+), 6 deletions(-) create mode 100644 src/main/webapp/resources/ng2/app/app.routing.ts create mode 100644 src/main/webapp/resources/ng2/app/owner-list.component.html create mode 100644 src/main/webapp/resources/ng2/app/owner-list.component.ts create mode 100644 src/main/webapp/resources/ng2/app/owner.service.ts create mode 100644 src/main/webapp/resources/ng2/app/owners.component.html create mode 100644 src/main/webapp/resources/ng2/app/owners.component.ts create mode 100644 src/main/webapp/resources/ng2/app/pet-list.component.ts diff --git a/src/main/webapp/resources/ng2/app/app.component.html b/src/main/webapp/resources/ng2/app/app.component.html index 5f89378..6f35e42 100644 --- a/src/main/webapp/resources/ng2/app/app.component.html +++ b/src/main/webapp/resources/ng2/app/app.component.html @@ -1,3 +1,3 @@ - + \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/app.module.ts b/src/main/webapp/resources/ng2/app/app.module.ts index 5f02d1c..05e16c5 100644 --- a/src/main/webapp/resources/ng2/app/app.module.ts +++ b/src/main/webapp/resources/ng2/app/app.module.ts @@ -5,11 +5,28 @@ import {AppComponent} from "./app.component"; import {WelcomeComponent} from "./welcome.component"; import {NavComponent} from "./nav.component"; import {FooterComponent} from "./footer.component"; +import {routing, appRoutingProviders} from "./app.routing"; +import {OwnersComponent} from "./owners.component"; +import {OwnerListComponent} from "./owner-list.component"; +import {PetListComponent} from "./pet-list.component"; +import {FormsModule} from "@angular/forms"; +import {HttpModule} from "@angular/http"; +import OwnerService from "./owner.service"; @NgModule({ - imports: [BrowserModule, NgbModule], - declarations: [AppComponent, WelcomeComponent, NavComponent, FooterComponent], - bootstrap: [AppComponent] + imports: [BrowserModule, FormsModule, HttpModule, NgbModule, routing], + providers: [appRoutingProviders, OwnerService], + bootstrap: [AppComponent], + declarations: [ + AppComponent, + WelcomeComponent, + NavComponent, + FooterComponent, + OwnersComponent, + OwnerListComponent, + PetListComponent + ], + }) export class AppModule { } \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/app.routing.ts b/src/main/webapp/resources/ng2/app/app.routing.ts new file mode 100644 index 0000000..5e8b72a --- /dev/null +++ b/src/main/webapp/resources/ng2/app/app.routing.ts @@ -0,0 +1,16 @@ +import {Routes, RouterModule} from "@angular/router"; +import {WelcomeComponent} from "./welcome.component"; +import {ModuleWithProviders} from "@angular/core"; +import {PetListComponent} from "./pet-list.component"; +import {OwnersComponent} from "./owners.component"; + +const appRoutes: Routes = [ + {path: '', pathMatch: 'full', redirectTo: '/welcome'}, + {path: 'welcome', component: WelcomeComponent}, + {path: 'owners', component: OwnersComponent}, + {path: 'pets', component: PetListComponent}, +]; + +export const appRoutingProviders: any[] = []; + +export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true}); \ No newline at end of file diff --git a/src/main/webapp/resources/ng2/app/nav.component.html b/src/main/webapp/resources/ng2/app/nav.component.html index 1b791ef..706b531 100644 --- a/src/main/webapp/resources/ng2/app/nav.component.html +++ b/src/main/webapp/resources/ng2/app/nav.component.html @@ -8,8 +8,12 @@