DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Modern Test Automation With AI (LLM) and Playwright MCP
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. How to Test Code That Uses Envers

How to Test Code That Uses Envers

By 
Nicolas Fränkel user avatar
Nicolas Fränkel
DZone Core CORE ·
Jun. 25, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
12.6K Views

Join the DZone community and get the full member experience.

Join For Free

Envers is a Hibernate module that can be configured to automatically audit changes made to your entities. Each audited entity are thus associated with a list of revisions, each revision capturing the state of the entity when a change occurs. There is however an obstacle I came across while I was "unit testing" my DAO, and that's what I want to share to avoid others to fall in the same pit. First, let's have an overview of the couple of steps needed to use Envers:

  • Annotate your entity with the @Audited annotation:
    @Entity
    @Audited
    public class Person {
    
        // Properties
    }
  • Register the Envers AuditEventListener in your Hibernate SessionFactory through Spring:
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="ch.frankel.blog.envers.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            </props>
        </property>
        <property name="schemaUpdate" value="true" />
        <property name="eventListeners">
            <map>
                <entry key="post-insert" value-ref="auditListener" />
                <entry key="post-update" value-ref="auditListener" />
                <entry key="post-delete" value-ref="auditListener" />
                <entry key="pre-collection-update" value-ref="auditListener" />
                <entry key="pre-collection-remove" value-ref="auditListener" />
                <entry key="post-collection-recreate" value-ref="auditListener" />
            </map>
        </property>
    </bean>
    
    <bean id="auditListener" class="org.hibernate.envers.event.AuditEventListener" />
  • Configure the Hibernate transaction manager as your transaction manager. Note auditing won't be triggered if you use another transaction manager (DataSourceTransactionManager comes to mind):
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
    </bean>
  • Now is the time to create your test class:
    @ContextConfiguration("classpath:spring-persistence.xml")
    @TransactionConfiguration(defaultRollback = false)
    public class PersonDaoImplTest extends AbstractTransactionalTestNGSpringContextTests {
    
        @Autowired
        private PersonDao personDao;
    
        @BeforeMethod
        protected void setUp() {
    
            // Populate database
        }
    
        @Test
        public void personShouldBeAudited() {
    
            Person person = personDao.get(1L);
    
            person.setFirstName("Jane");
    
            List<Person> history = personDao.getPersonHistory(1L);
    
            assertNotNull(history);
            assertFalse(history.isEmpty());
            assertEquals(history.size(), 1);
        }
    }

Strangely, when you execute the previous test class, the test method fails when checking the list is not empty: it is, meaning there's no revision associated with the entity. Morevoer, nothing shows up in the log. However, the revision shows up in the audited table at the end of the test (provide you didn't clear the table after its execution). Comes the dreaded question: why? Well, it seems Hibernate post-event listeners are only called when the transaction is commited. In our case, it matches: the transaction is commited by Spring after method completion, and our test trie to assert inside the method. In order for our test to pass, we have to manually manage a transaction inside our method, to commit the update to the database.

@Test
public void personShouldBeAuditedWhenUpdatedWithManualTransaction() {

    PlatformTransactionManager txMgr = applicationContext.getBean(PlatformTransactionManager.class);

	// A new transaction is required, the wrapping transaction is for Envers
    TransactionStatus status = txMgr.getTransaction(new DefaultTransactionDefinition(PROPAGATION_REQUIRES_NEW));

    Person person = personDao.get(1L);

    person.setFirstName("Jane");

    txMgr.commit(status);

    List<Person> history = personDao.getPersonHistory(1L);

    assertNotNull(history);
    assertFalse(history.isEmpty());
    assertEquals(history.size(), 1);
}

On one hand, the test passes and the log shows the SQL commands accordingly. On the other hand, the cost is the additional boilerplate code needed to make it pass. Of course, one could (should?) question the need to test the feature in the first place. Since it's a functionality brought by a library, the reasoning behind could be that if you don't trust the library, don't use it at all. In my case, it was the first time I used Envers, so there's no denying I had to build the trust between me and the library. Yet, even with trusted libraries, I do test specific cases: for example, when using Hibernate, I create test classes to verify that complex queries get me the right results. As such, auditing qualifies as a complex use-case whose misbehaviors I want to be aware of as soon as possible. You'll find the sources for this article here, in Maven/Eclipse format.

Testing

Opinions expressed by DZone contributors are their own.

Related

  • Modern Test Automation With AI (LLM) and Playwright MCP
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!