Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unit testing with Hibernate without a running database

 
Colin Shine
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have only used Hibernate on one project before, and I found that Unit Testing was a right pain the . Are there any good patterns, maybe DAO interfaces that would allow me to perform unit tests without actually having a database up and running?
 
Eric Burke
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I try to write as many tests as possible without hitting the database. For example, your persistent classes will often have many helper methods, such as methods to ensure bidirectional associations are setup correctly. These don't need any database and are testable as with any normal POJO.

Once you start hitting the db, many tests can be written by starting a transaction in setUp(), then rolling back in tearDown(). This way you don't leave clutter behind in the database.

If you need to do more advanced data testing, you're probably venturing into something other than "unit" testing. I don't think there is anything specific to Hibernate that you won't see with any other database access approach. You still need to set up well-known test data, run your tests, then restore the database to a known point.
 
Patrick Peak
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The basic question is "What are you trying to test?"

1) Is your HQL written correctly?
2) Are your objects mapping correctly?
3) Your actions (or whatever) that use DAO's (which happen to do Hibernate stuff).

For 1 and 2, you need a database really. Hiding the HQL away in a DAO is a good way to solve #3. Having a DAO allows you to stub in a dummy DAO that just returns the objects you want, without the need to go to the database.

We actually wrote a whole chapter about this in Hibernate Quickly, which might be useful.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic