Testing Databases with JUnit and Hibernate Part 1: One to Rule them

Databases are an extremely important part of almost every enterprise application. Yet there is very little support for testing your database, which results in very little tests coverage of database related code out in the wild. In a desperate attempt to change that at least a little the article series starting with this article will describe some of the problems and possible partial solutions based on Hibernate and JUnit.
As an example I use the following little set of Hibernate entity classes and the database schema Hibernate will create from it:

  1. @Entity
  2. public class SuperHero extends AbstractEntity {
  3.  
  4.  @NotEmpty
  5.  @Column(unique = true)
  6.  public String name;
  7.  
  8.  @ManyToOne
  9.  @NotNull
  10.  public SuperPower power;
  11.  
  12.  @NotEmpty
  13.  public String weakness;
  14.  
  15.  @NotEmpty
  16.  public String secretIdentity;
  17. }
  1. @Entity
  2. public class SuperPower extends AbstractEntity {
  3.  
  4.  @NotEmpty
  5.  @Column(unique = true)
  6.  public String name;
  7.  
  8.  @NotEmpty
  9.  public String description;
  10.  
  11.  @NotNull
  12.  @ManyToOne
  13.  public SuperPowerType type;
  14. }
  1. @Entity
  2. public class SuperPowerType extends AbstractEntity {
  3.  
  4.  @NotEmpty
  5.  @Column(unique = true)
  6.  public String name;
  7.  
  8.  @NotNull
  9.  @Length(min = 30)
  10.  public String description;
  11. }

As you can see (and if you don’t I tell you) a SuperHero references a SuperPower and a SuperPower references a SuperPowerType. All have some mandatory attributes.
All three entities have a common supertype providing id and version.

  1. @MappedSuperclass
  2. public class AbstractEntity {
  3.  
  4.  @SuppressWarnings("unused")
  5.  @Id
  6.  @GeneratedValue
  7.  public Long id;
  8.  @SuppressWarnings("unused")
  9.  @Version
  10.  private Long version;
  11. }

For brevity I skipped on getters and setters.

Finally there is a SuperHeroRepository which I want to test. It has a single method returning a SuperHero based on the a SuperPower
A simple test for the SuperHeroRepository might work like this:

Create a SuperHero and make sure I can retrieve it again using the SuperHeroRepository.

Easy, isn’t it? Well … lets see what you really have to do

  • create an empty database
  • create a SuperPowerType, making sure you have all the mandatory fields filled
  • create a SuperPower of that type, making sure you have all the mandatory fields filled
  • create a SuperHero, making sure you have all the mandatory fields filled
  • use the repository to retrieve SuperHeros
  • assert you got the expected result.

So we have to fill all the mandatory fields and provide a SuperPowerType (again with all the mandatory fields) although nothing in the test is concerned with SuperPowerTypes. If you still don’t believe this results in ugly code have a look at this naive implementation.

  1. public class SuperHeroRepository1Test {
  2.  private SessionFactory sessionFactory;
  3.  private Session session = null;
  4.  
  5.  @Before
  6.  public void before() {
  7.   // setup the session factory
  8.   AnnotationConfiguration configuration = new AnnotationConfiguration();
  9.   configuration.addAnnotatedClass(SuperHero.class)
  10.     .addAnnotatedClass(SuperPower.class)
  11.     .addAnnotatedClass(SuperPowerType.class);
  12.   configuration.setProperty("hibernate.dialect",
  13.     "org.hibernate.dialect.H2Dialect");
  14.   configuration.setProperty("hibernate.connection.driver_class",
  15.     "org.h2.Driver");
  16.   configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem");
  17.   configuration.setProperty("hibernate.hbm2ddl.auto", "create");
  18.  
  19.   sessionFactory = configuration.buildSessionFactory();
  20.   session = sessionFactory.openSession();
  21.  }
  22.  
  23.  @Test
  24.  public void returnsHerosWithMatchingType() {
  25.  
  26.   // create the objects needed for testing
  27.   SuperPowerType powerType = new SuperPowerType();
  28.   powerType.name = "TheType";
  29.   powerType.description = "12345678901234567890aDescription";
  30.  
  31.   SuperPower superpower = new SuperPower();
  32.   superpower.name = "SuperPower";
  33.   superpower.description = "Description";
  34.   superpower.type = powerType;
  35.  
  36.   SuperHero hero = new SuperHero();
  37.   hero.name = "Name";
  38.   hero.power = superpower;
  39.   hero.weakness = "None";
  40.   hero.secretIdentity = "Mr. Jones";
  41.  
  42.   // storing the objects for the test in the database
  43.   session.save(powerType);
  44.   session.save(superpower);
  45.   session.save(hero);
  46.  
  47.   SuperHeroRepository heroRepository = new SuperHeroRepository(session);
  48.   List<SuperHero> heroes = heroRepository.loadBy(superpower);
  49.   assertNotNull(heroes);
  50.   assertEquals(1, heroes.size());
  51.  }
  52.  
  53.  @After
  54.  public void after() {
  55.   session.close();
  56.   sessionFactory.close();
  57.  }
  58. }

There is really only one positive thing I can say about this test: it uses H2 in In-Memory mode so it is reasonable fast. There is the first lesson: *Use an in memory database for testing if possible. It’s easily 100*faster then a disc based database*

So obviously we want to refactor this monster, which might after some method extracting result into something like this:

  1. public class SuperHeroRepository2Test {
  2.  
  3.  private SessionFactory sessionFactory;
  4.  private Session session;
  5.  
  6.  @Before
  7.  public void before() {
  8.   sessionFactory = createSessionFactory();
  9.   session = sessionFactory.openSession();
  10.   Transaction transaction = session.beginTransaction();
  11.  }
  12.  
  13.  @Test
  14.  public void returnsHerosWithMatchingType() {
  15.  
  16.   SuperPowerType powerType = createSuperPowerType();
  17.   session.save(powerType);
  18.  
  19.   SuperPower superpower = createSuperPower(powerType);
  20.   session.save(superpower);
  21.  
  22.   SuperHero hero = createSuperHero(superpower);
  23.   session.save(hero);
  24.  
  25.   SuperHeroRepository heroRepository = new SuperHeroRepository(session);
  26.   List<SuperHero> heroes = heroRepository.loadBy(superpower);
  27.  
  28.   assertNotNull(heroes);
  29.   assertEquals(1, heroes.size());
  30.  }
  31.  
  32.  private SessionFactory createSessionFactory() {
  33.   AnnotationConfiguration configuration = new AnnotationConfiguration();
  34.   configuration.addAnnotatedClass(SuperHero.class)
  35.     .addAnnotatedClass(SuperPower.class)
  36.     .addAnnotatedClass(SuperPowerType.class);
  37.   configuration.setProperty("hibernate.dialect",
  38.     "org.hibernate.dialect.H2Dialect");
  39.   configuration.setProperty("hibernate.connection.driver_class",
  40.     "org.h2.Driver");
  41.   configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem");
  42.   configuration.setProperty("hibernate.hbm2ddl.auto", "create");
  43.  
  44.   SessionFactory sessionFactory = configuration.buildSessionFactory();
  45.   return sessionFactory;
  46.  }
  47.  
  48.  private SuperHero createSuperHero(SuperPower superpower) {
  49.   SuperHero hero = new SuperHero();
  50.   hero.name = "Name";
  51.   hero.power = superpower;
  52.   hero.weakness = "None";
  53.   hero.secretIdentity = "Mr. Jones";
  54.   return hero;
  55.  }
  56.  
  57.  private SuperPower createSuperPower(SuperPowerType powerType) {
  58.   SuperPower superpower = new SuperPower();
  59.   superpower.name = "SuperPower";
  60.   superpower.description = "Description";
  61.   superpower.type = powerType;
  62.   return superpower;
  63.  }
  64.  
  65.  private SuperPowerType createSuperPowerType() {
  66.   SuperPowerType powerType = new SuperPowerType();
  67.   powerType.name = "TheType";
  68.   powerType.description = "12345678901234567890aDescription";
  69.   return powerType;
  70.  }
  71. }

This would be ok, if this would be the only test of this kind. But other similar test need the SessionFactory as well so I will move all the SessionFactory, Session and Transaction stuff into a Rule

  1. public class SessionFactoryRule implements MethodRule {
  2.  private SessionFactory sessionFactory;
  3.  private Transaction transaction;
  4.  private Session session;
  5.  
  6.  @Override
  7.  public Statement apply(final Statement statement, FrameworkMethod method,
  8.    Object test) {
  9.   return new Statement() {
  10.  
  11.    @Override
  12.    public void evaluate() throws Throwable {
  13.     sessionFactory = createSessionFactory();
  14.     createSession();
  15.     beginTransaction();
  16.     try {
  17.      statement.evaluate();
  18.     } finally {
  19.      shutdown();
  20.     }
  21.    }
  22.  
  23.   };
  24.  }
  25.  
  26.  private void shutdown() {
  27.   try {
  28.    try {
  29.     try {
  30.      transaction.rollback();
  31.     } catch (Exception ex) {
  32.      ex.printStackTrace();
  33.     }
  34.     session.close();
  35.    } catch (Exception ex) {
  36.     ex.printStackTrace();
  37.    }
  38.    sessionFactory.close();
  39.   } catch (Exception ex) {
  40.    ex.printStackTrace();
  41.   }
  42.  }
  43.  
  44.  private SessionFactory createSessionFactory() {
  45.   AnnotationConfiguration configuration = new AnnotationConfiguration();
  46.   configuration.addAnnotatedClass(SuperHero.class)
  47.     .addAnnotatedClass(SuperPower.class)
  48.     .addAnnotatedClass(SuperPowerType.class);
  49.   configuration.setProperty("hibernate.dialect",
  50.     "org.hibernate.dialect.H2Dialect");
  51.   configuration.setProperty("hibernate.connection.driver_class",
  52.     "org.h2.Driver");
  53.   configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem");
  54.   configuration.setProperty("hibernate.hbm2ddl.auto", "create");
  55.  
  56.   SessionFactory sessionFactory = configuration.buildSessionFactory();
  57.   return sessionFactory;
  58.  }
  59.  
  60.  public Session createSession() {
  61.   session = sessionFactory.openSession();
  62.   return session;
  63.  }
  64.  
  65.  public void commit() {
  66.   transaction.commit();
  67.  }
  68.  
  69.  public void beginTransaction() {
  70.   transaction = session.beginTransaction();
  71.  }
  72.  
  73.  public Session getSession() {
  74.   return session;
  75.  }
  76. }

Which leaves the test in a somewhat acceptable state.

  1. public class SuperHeroRepository3Test {
  2.  
  3.  @Rule
  4.  public final SessionFactoryRule sf = new SessionFactoryRule();
  5.  
  6.  @Test
  7.  public void returnsHerosWithMatchingType() {
  8.   Session session = sf.getSession();
  9.  
  10.   SuperPowerType powerType = createSuperPowerType();
  11.   session.save(powerType);
  12.  
  13.   SuperPower superpower = createSuperPower(powerType);
  14.   session.save(superpower);
  15.  
  16.   SuperHero hero = createSuperHero(superpower);
  17.   session.save(hero);
  18.  
  19.   sf.commit();
  20.  
  21.   SuperHeroRepository heroRepository = new SuperHeroRepository(session);
  22.   List<SuperHero> heroes = heroRepository.loadBy(superpower);
  23.  
  24.   assertNotNull(heroes);
  25.   assertEquals(1, heroes.size());
  26.  }
  27.  
  28.         // … private methods more or less as before
  29. }

All the SessionFactory creation is now moved out into a Rule and is therefore perfectly reusable. You now can change the way you create your SessionFactory at a single point for all tests in need of a database. This is nice and it shall be enough for today. Next week we’ll take care of our SuperHero and her dependencies.

Share:
  • DZone
  • Digg
  • del.icio.us
  • Reddit
  • Facebook
  • Twitter