PDA

View Full Version : Unit testing Hibernate DAOs in Spring



mueller
Mar 15th, 2008, 10:48 AM
I really love how Spring makes unit testing so easy with dependency injection and database testing infrastructure like the AbstractTransactionalDataSourceSpringContextTests class. However, I'm having some trouble testing inserting data using hibernate.

If I want to test an addThing method, this is how I'd imagine doing it:

long id = thingDao.addThing(oldThing);
Thing newThing = thingDao.getThing(id);
assertEquals("Name should be same", oldThing.getName(), newThing.getName());

For code like above, I'd get an org.hibernate.NonUniqueObjectException stating "a different object with the same identifier value was already associated with the session." So how do I do the very necessary test of seeing if a row was inserted properly?

miluch
Mar 17th, 2008, 05:21 AM
Here: http://today.java.net/pub/a/today/2005/10/11/testing-hibernate-mapping.html
yuo can find article that shed some light on testing with hibernate...
Although it describes testing mapping it provides solution for your problem.
I believe clear session before retrieving from DB is enough

mueller
Mar 17th, 2008, 02:40 PM
Thank you miluch, I cast my injected Dao to the implementing hibernate-based class and called sessionFactory.getCurrentSession().flush() and then .clear(). Now my unit tests pass.

Now I have a different problem the article you presented actually somewhat addresses. Not quite though, so I'll post this in another thread here.