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:

@Component
public class CandidateListener implements PreUpdateEventListener {

@Autowired
EntityManagerFactory entityManagerFactory;

@PostConstruct
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);
}

@Override
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:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@Transactional
public class CandidateListenerTest {

@Autowired
CandidateRepository candidateRepository;

@Autowired
EntityAuditEventRepository entityAuditEventRepository;

@Autowired
SessionFactory sessionFactory;

@Test
public void testHistoryLogging() {
    Candidate cand = new Candidate();
    cand.setEmail("123@gmail.com");
    cand.setFirstName("12");
    cand.setLastName("3");

    cand = candidateRepository.save(cand);

    cand.setLastName("34");
    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.