Testing object-relational mappings

When using Hibernate, it’s useful to include an integration test that builds an object model, saves it and retrieves it from the database. What frequently causes problems when using Hibernate (or object-relational mappings in general) is that 3 different things must be kept in sync:

  1. an object model;
  2. a database schema;
  3. the mapping files (or Java annotations etc) that link the other two.

It is very easy to miss the moment when they get out of step if you only have unit tests that don’t use a real database.

If you use this kind of test it can also free you to write much simpler unit tests that use non-persistent versions of objects rather than writing slower and more complicated database-backed tests. Database-backed tests in particular can make it much more difficult to diagnose the true source of a test failure when the database has been left in an inconsistent state (this can be avoided by correctly tearing down persistent state between test runs but this is rarely done correctly).