Hibernate’s PreUpdateEventListener not being called in unit tests

I am trying to test my PreUpdateEventListener flow, but I cannot seem to make it work in the JUnit tests. I am not getting any error, but the code is not called.

My PreUpdateEventListener:

public class CandidateListener implements PreUpdateEventListener {

EntityManagerFactory entityManagerFactory;

private void init() {
    HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) this.entityManagerFactory;
    SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
    EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
    registry.appendListeners(EventType.POST_LOAD, this);
    registry.appendListeners(EventType.PRE_UPDATE, this);

public boolean onPreUpdate(PreUpdateEvent event) {
    final Object entity = event.getEntity();
    if (entity == null) return false;

    // code here not being called in unit tests, but works fine on server

    return false;


The test:

@SpringApplicationConfiguration(classes = Application.class)
public class CandidateListenerTest {

CandidateRepository candidateRepository;

EntityAuditEventRepository entityAuditEventRepository;

SessionFactory sessionFactory;

public void testHistoryLogging() {
    Candidate cand = new Candidate();

    cand = candidateRepository.save(cand);


    assertEquals(entityAuditEventRepository.findAll().size(), 1);


I have tried injecting the SessionFactory into the test and calling SessionFactory#flush method, but that throws No CurrentContextSession error, which I cannot seem to fix.

Source: java

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.