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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • Advanced Functional Testing in Spring Boot Using Docker in Tests
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 4)
  • Setting Up a CrateDB Cluster With Kubernetes to Store and Query Machine Data

Trending

  • Understanding Java Signals
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • The Role of Functional Programming in Modern Software Development
  • How Clojure Shapes Teams and Products
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Testing the Hibernate Layer With Docker

Testing the Hibernate Layer With Docker

We are all writing unit tests for the service layer, but the persistence layer, in contrast, is rarely tested. Luckily, Docker offers TestContainers.

By 
Kai Winter user avatar
Kai Winter
·
Jun. 09, 16 · Analysis
Likes (4)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

This article was updated in March 2023 for Java 17, Hibernate 6, JUnit 5, and Testcontainers 1.17.6.

Have you ever felt the need to write unit tests for your persistence layer? We know logic doesn’t belong there. It should just do some CRUD operations and nothing more. But in reality, some kind of logic can be found in most persistence layers. Some use heavy native SQL, while others make use of the Criteria API, which is test-worthy because of its complex syntax.

We are all writing unit tests for the service layer but the persistence layer, in contrast, is rarely tested as it is more complicated to test SQL or JPQL... or any other QL’es.

An Example

One example of logic that better be tested is the following. This is a trivial example which may be far more complex in reality. I’ll use this to demonstrate how to test persistence-related code.

Java
 
/**
 * Resets the login count for other users than root and admin.
 */
public void resetLoginCountForUsers() {
   Query query = entityManager.createQuery(
                   "UPDATE User SET loginCount=0 WHERE username NOT IN ('root', 'admin')");
   query.executeUpdate();
}


Previously in Our Toolbox

In the past, there were several approaches to testing the persistence layer:

  • In memory databases like HSQL
    • Pro: Clean database on every run
    • Con: Different database than in production (Oracle, MySQL, …)
    • Con: Doesn’t work when you need stored procedures
  • Local database on the dev machine
    • Pro: Same database as production
    • Con: Have to take care of deleting previous data
    • Con: Possible side effects when the database is used for development also
    • Con: Have to synchronize settings on dev machines and CI system
  • Dummy database driver, which returns pseudo data from CSV files
    • Pro: Lightweight
    • Con: It is hard to set up for a large domain model. The model might be invalid.

New Kid on the Block: TestContainers

Testcontainers for Java is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container. [testcontainers.org]

This library starts a Docker container, which contains any database you like. Your tests get a connection to that database, and you can start inserting your test data per each single unit test.

  • Pro: Absolutely reproducible test
  • Pro: Same database as in production
  • Pro: Configuration is shared above all machines via the docker image
  • Con: A bit slower because of database start (depending on the used database)
  • Con: You need a Docker host against which the tests can run. This may either be centralized so all developers are using the same (which is no problem even when starting containers concurrently), or you have a Docker installation on your local machine.

This is what the test looks like. The data model is already inserted (by persistence.xml, see below), the test inserts its test data by DbUnit (line 3), calls the persistence layer method (line 8), and makes the assertions (lines 15-17). The transactions have to be managed by hand (lines 7, 9) as we have no container which is doing this for us. To make this more convenient, the transaction management can be wrapped in a method and a lambda function, like runWithTransaction(() -> userRepository.resetLoginCountForUsers());

Java
 
@Test
void testResetLoginCountForUsers() {
   DockerDatabaseTestUtil.insertDbUnitTestdata(
     entityManager, 
     getClass().getResourceAsStream("/testdata.xml));

   entityManager.getTransaction().begin();
   userRepository.resetLoginCountForUsers();
   entityManager.getTransaction().commit();

   User rootUser = userRepository.findByUsername("root");
   User adminUser = userRepository.findByUsername("admin");
   User user = userRepository.findByUsername("user");

   assertEquals(5, rootUser.getLoginCount());
   assertEquals(3, adminUser.getLoginCount());
   assertEquals(0, user.getLoginCount()); // PREVIOUSLY WAS 1
}


Using TestContainers

First, the persistence.xml is prepared to use a special driver that comes with the JDBC module of TestContainers.

Java
 
<properties>
  <property 
    name="jakarta.persistence.jdbc.driver"
    value="org.testcontainers.jdbc.ContainerDatabaseDriver"/>
  <property 
    name="jakarta.persistence.jdbc.url"
    value="jdbc:tc:mysql:5.7://xxx/test?TC_INITSCRIPT=DDL.sql"/>
</properties>


The driver org.testcontainers.jdbc.ContainerDatabaseDriver is registered in the JDBC module. It evaluates thejdbc.url to start the right docker image. In this case, mysql:5.7. The suffix ?TC_INITSCRIPT=DDL.sql initializes the database with the DB model. There are also other ways to initialize the database (see below).

The initialization is triggered by Hibernate with the creation of the EntityManager in the test:

Java
 
EntityManager em = Persistence.createEntityManagerFactory("TestUnit").createEntityManager();


This will make Hibernate parse the persistence.xml and look up the JDBC driver, which triggers TestContainers to start the MySQL Docker container. (The database’s port is exposed on a random port.) The resulting EntityManager is pointing to the started and initialized Docker container and can be used:

Java
 
class UserTest {
   EntityManager entityManager = Persistence.createEntityManagerFactory("TestPU").createEntityManager();

   @Test
   void testSaveAndLoad() {
      User user = new User();
      user.setUsername("user 1");

      entityManager.getTransaction().begin();
      entityManager.persist(user);
      entityManager.getTransaction().commit();

      User userFromDb = entityManager.find(User.class, user.getId());
      assertEquals(user.getUsername(), userFromDb.getUsername());
   }
}


The complete test class is here: UserTest

The complete test from the beginning, which calls the repository, is here: UserRepositoryTest

Different Ways To Insert the Data Model and Test Data

There are several ways to get your data model and test data into the database.

  • As seen before, the connection string in the persistence.xml: The property suffix ?TC_INITSCRIPT=DDL.sql initializes the database with the DB model from DDL.sql
  • Execute SQL File(s) from your test, see DockerDatabaseTestUtil.insertSqlFile()
  • Execute single SQL Queries from your test, see DockerDatabaseTestUtil.insertSqlString()
  • Use DbUnit to insert test data from XML files, see DockerDatabaseTestUtil.insertDbUnitTestdata()
  • The model can also be generated by Hibernate by setting the property in the persistence.xml hibernate.hbm2ddl.auto

My favorite is to insert the DDL via the persistence.xml and then let every test case insert its own data by DbUnit.

You can find the complete code examples on GitHub.

What’s Next

Was this article useful for you? Please share your thoughts in the comments. Follow my account, and you will be notified about my upcoming article on using TestContainers to deploy to a Wildfly server running in a Docker container.

Docker (software) Database unit test Hibernate Test data

Published at DZone with permission of Kai Winter. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • Advanced Functional Testing in Spring Boot Using Docker in Tests
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 4)
  • Setting Up a CrateDB Cluster With Kubernetes to Store and Query Machine Data

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!