Search code examples
springhibernateintegration-testingunitils

Integration Test Strategy for Create methods


I want to test if created entity has been correctly persisted to database.There is a service integration test for create method:

@SpringApplicationContext({"setting ...."})
public class PersonServiceIntegrationTest extends UnitilsJUnit4 {
     @SpringBeanByName
     private PersonService personService;
     @Test
     public void createPerson() {
        String name = "Name";
        String sname = "Surename";
        DtoPerson item = personService.createPerson(name, sname, Arrays.asList( new DtoAddress("Pisek","CZE", true), new DtoAddress("Strakonice", "CZE", false) );
        Assert.notNull("Cannot be null", item);
        /* 
         *  This assertion fails because of transaction (I suppose) - item is not in
         *  database right now. 
         *  Why? Returned dto 'item; is not null?
         */
        //domain with all fetched related entities, eg. address
        Person p = personService.getPerson(item.getIdPerson());
        List<Address> addresses = p.getAddresses();
        Assert.notNull("Cannot be null", p);
        Assert.notNull("Cannot be null", addresses);//return collection of Address
        Assert.notFalse("Cannot be emtpty", addresses.isEmpty());
        ReflectionAssert.assertPropertyLeniens("City", Arrays.asList("Pisek", "Strakonice"), addresses);
     }
}
  1. Is it necessary to test create entity if I use hibernate? Someone can write you try to test low-level hibernate but hibernate has own tests. There is a trivial code above but I can imagine some specific code which persists more entites at same time (eg. one-many plus several one-one relations). And I want to test if relations has been correctly persisted.

  2. Is there a pattern to do test this way? I have a problem, that record is not at database. I don't want to use returned dto (it presents only agregate root entity - person, but it does not say about person basic data (one-many), person address (one-many) etc.)... i want to get persisted record.


Solution

  • What I do to test the persistence is:

    • 1) I create the Domain entity,
    • 2) save it with Hibernate/JPA,
    • 3) flush and clear the hibernate session/entity manager
    • 4) load the entity again with hibernate
    • 5) compare the original entity with the one that I have (re)loaded

    so I am pretty sure that the mapping is more or less correct and every thing get persisted