Importance of flushing data in unit test cases

While writing unit tests it is a good practice to clear and flush the session. When application is executed in real time there are several request and response or different transactions due to which the session/cache gets cleared. However while running unit test, everything happens as the part of single process ie the session (especially hibernate) has rotten values or old references which gives some exceptions at times.

Exception :
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.ptc.fusion.model.learningitem.OnlineCourse#1]
at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:613)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate

Code Example :

learningItemRepository.saveLearningItem(c3);

sessionFactory.getCurrentSession().flush();
sessionFactory.getCurrentSession().clear();

Map<FusionLocale, RootLearningItem> mapBeforeUnMapping = learningItemService.findEquivalentLearningItems(c2);
assert mapBeforeUnMapping.size() == 2;
assert mapBeforeUnMapping.values().contains(c1);
assert mapBeforeUnMapping.values().contains(c2);

sessionFactory.getCurrentSession().flush();
sessionFactory.getCurrentSession().clear();

boolean unMappingSuccessful = learningItemService.unMapEquivalentLearningItem(c1);
assert  unMappingSuccessful;

Hence it is always a good practice to clear/flush session after repository calls or hibernate transactions to make unit test case robust.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s