Integration testing native SQL query when using Hibernate

I use Hibernate and widely adopted Hibernate Query Language to define queries in my DAOs.

Anyway sometimes HQL isn’t capable of performing specific task compared to native SQL query.

For example the following Postgres expression is not “convertible” to HQL:

my_date > current_date - interval '10 year'

This means that in some case I’m writing native queries. Considering that I’m using another database for integration testing (http://hsqldb.org/) which doesn’t reflect the syntax of the Postgres expression above. This results in test exception during DAO methods using such native query.

How do you handle such cases? I can just think of following scenarios:

  • Never use native query and try to build everything in HQL (possible?)
  • Don’t test methods which use such queries (unhappy)
  • Use same database both for production and development (performance problem)

Other, more interesting solution? Thanks

Answer

Normally the purpose of integration testing is to test against (very) similar environment to production, hence IMO you should use the same database engine. For unit testing however using HSQLDB is fine. In which case unfortunately the classes that has dependency to Postgres couldn’t be unit tested, you have to wait until integration testing to detect bugs.

On a side note however the result of the Postgres SQL you mentioned can be achieved by performing the date arithmetic on Java.

Calendar currentDateCal = Calendar.getInstance();
currentDateCal.add(Calendar.YEAR, -10);
Date currentDate = currentDateCal.getTime(); // bind this currentDate object into your HQL parameter

Leave a Reply

Your email address will not be published. Required fields are marked *