Testing Databases with JUnit and Hibernate Part 2: The Mother of All Things

In the first part of this little series I showed a simple test based on a simple data model. As we saw the code for the test wasn’t simple at all, but quite ugly. We started to fix that by moving out all the SessionFactory and Session handling stuff out into a Rule. Leaving us with test code like this:

Since we won’t be satisfied with a single test we’ll wan’t to reuse the createXXX methods. The starting idea for how to do this comes from Martin Fowler. He describes ObjectMothers as objects wich give birth to complex objects needed for testing. This is exactly the information we are in. So the createXXX Methods should go to ObjectMothers. As you can see in the current version of the test, there are two things an ObjectMother must do:

create Instances of a class that have all attributes filled in a way that satisfies the constraints present in the database.

store them in the hibernate session.

So here is a very simple version of such an ObjectMother:

publicclass SuperPowerTypeMother {

privatefinal Session session;

public SuperPowerTypeMother(Session s){

session = s;

}

public SuperPowerType instance(){

SuperPowerType powerType = new SuperPowerType();

powerType.name = "TheType";

powerType.description = "12345678901234567890aDescription";

session.save(powerType);

return powerType;

}

}

This gets used by the ObjectMother for SuperPowers:

publicclass SuperPowerMother {

privatefinal Session session;

public SuperPowerMother(Session s){

session = s;

}

public SuperPower instance(){

SuperPower superpower = new SuperPower();

superpower.name = "SuperPower";

superpower.description = "Description";

superpower.type = new SuperPowerTypeMother(session).instance();

session.save(superpower);

return superpower;

}

}

Finally add a similar SuperHeroMother and our test looks like this:

publicclass SuperHeroRepository4Test {

@Rule

publicfinal SessionFactoryRule sf = new SessionFactoryRule();

@Test

publicvoid returnsHerosWithMatchingType(){

SuperHero hero = new SuperHeroMother(sf.getSession()).instance();

sf.commit();

SuperHeroRepository heroRepository = new SuperHeroRepository(

sf.getSession());

List<SuperHero> heroes = heroRepository.loadBy(hero.power);

assertNotNull(heroes);

assertEquals(1, heroes.size());

}

}

This is nice. Short and concentrated on what we want to test. Only the session hints at the presence of the database. Also when our entities get new attributes we have a single place to set a default value for that attribute for all our tests. All thats left in the test for creating a SuperHero is a one liner like this:

SuperHero hero = new SuperHeroMother(sf.getSession()).instance();

So are we done? No, because the ObjectMothers have two serious problems:

they create new entities every time, which will result in unique constraint violations once you deal with more then one SuperHero

they set the attributes in the same way every time, but sooner or later you want a hero with a special SuperPower, so we want to specify some attributes we are interested in without worrying about the others.

In order to solve the first problem mothers must look in the database if an instance as the one requested is already present. For this the alternate key of the entity is used, and only if a select with this alternate key doesn’t return an entity a new one is created. Note that since each entity gets stored in the session before it leaves the mother each such lookup select causes a flush of the session and therefore sees previously created entities.

In order to set attributes of the entities a builder pattern is used. The mothers have a method named after the attribute, taking an attribute value, and returning the mother instance.

So the SuperHeroObjectMother now looks like this.

publicclass SuperHeroMother {

privatefinal Session session;

privateString secretIdentity = "Mr. Jones";

privateString name = "Name";

privateString weakness = "None";

private SuperPower power = null;

public SuperHeroMother(Session s){

session = s;

power = new SuperPowerMother(session).instance();

}

public SuperHero instance(){

SuperHero hero = loadInstance();

if(hero == null){

hero = createInstance();

}

hero.power = power;

hero.weakness = weakness;

hero.secretIdentity = secretIdentity;

session.save(hero);

return hero;

}

private SuperHero loadInstance(){

return(SuperHero) session.createCriteria(SuperHero.class)

.add(Restrictions.eq("name", name)).uniqueResult();

}

private SuperHero createInstance(){

SuperHero hero = new SuperHero();

hero.name = name;

return hero;

}

public SuperHeroMother name(String aName){

name = aName;

returnthis;

}

public SuperHeroMother secretIdentity(String aSecretIdentity){

secretIdentity = aSecretIdentity;

returnthis;

}

public SuperHeroMother power(SuperPower aPower){

power = aPower;

returnthis;

}

public SuperHeroMother weaknes(String aWeakness){

weakness = aWeakness;

returnthis;

}

}

Using such an object mother is extremely easy: create a mother instance, set the attributes you are interested in and call instance().

But writing a Mother is a little tedious and if done as shown above involves a lot of code duplication. So in the next part of the series we’ll do some refactoring in order to remove at least some of the code duplication.