Importance of flushing data in unit test cases

Aseem Jain

While writing unit test cases, it is a good practice to clear and flush the session. When an application is executed in real time, there are several requests, responses or different transactions due to which the session/cache gets cleared. On the other hand, while running a unit test, everything happens as part of a single process i.e the session (especially hibernate) has rotten values or old references which leads to raising of certain 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( at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate

Code Example :
sessionFactory.getCurrentSession().flush(); sessionFactory.getCurrentSession().clear();
MapmapBeforeUnMapping = 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 a unit test case robust.