It's not a secret anymore!
The moose likes Object Relational Mapping and the fly likes Unit testing with Hibernate without a running database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Unit testing with Hibernate without a running database" Watch "Unit testing with Hibernate without a running database" New topic

Unit testing with Hibernate without a running database

Colin Shine

Joined: Aug 12, 2005
Posts: 26
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

Joined: May 12, 2003
Posts: 7
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

Joined: Aug 23, 2005
Posts: 19
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.

Hibernate Quickly - <a href="" target="_blank" rel="nofollow"></a>
I agree. Here's the link:
subject: Unit testing with Hibernate without a running database
jQuery in Action, 3rd edition