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

  • JSON-Based Serialized LOB Pattern
  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2
  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Using AUTHID Parameter in Oracle PL/SQL

Trending

  • Java Virtual Threads and Scaling
  • Understanding Java Signals
  • Develop a Reverse Proxy With Caching in Go
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  1. DZone
  2. Data Engineering
  3. Databases
  4. Persistence and DAO Testing Made Simple (with Exparity-Stub and Hamcrest-Bean)

Persistence and DAO Testing Made Simple (with Exparity-Stub and Hamcrest-Bean)

By 
Stewart Bissett user avatar
Stewart Bissett
·
Jun. 29, 15 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
2.9K Views

Join the DZone community and get the full member experience.

Join For Free

Persistence of model objects is a part of many Java projects and a part which deserves, and often gets, high test coverage as one of the key layer integration points in the code. However, I've often felt the testing paradigms for this can be cumbersome, often involving a large amount of setup with an equivalent amount of validation. This can be tedious to both create and maintain. As a solution to this I've been testing persistence with a different pattern; by combining both the exparity-stub and the hamcrest-bean library you can thoroughly test model persistence in a few lines of test code as per the snippet below;  

..
User user = aRandomInstanceOf(User.class);
User saved = dao.save(user);
assertThat(dao.getUserById(saved.getId()), theSameBeanAs(saved));

The test snippet above is small but in those few lines will thoroughly test that all fields in a graph can be persisted and retrieved without loss, that any JPA or other mapping is valid, and that your queries are valid. For a complete example we'll work through testing a simple DAO for storing and retrieving User objects using the in-memory H2 database for simplicity. The same example will work for any persistence mechanism. Before we get started with an example lets briefly outline what the libraries are and what they do.

The Exparity-Stub Library

The exparity-stub libraries provides a set of static methods for creating stubs of model objects, object graphs, collections, types, and primitive types. For our example we'll be creating random stubs because we want to completely fill the graph with junk data and check it can be written down. exparity-stub offers two approaches to this, the RandomBuilder or the BeanBuilder. The RandomBuilder provides a terser notation to create random objects with less code. For example:

User user = RandomBuilder.aRandomInstanceOf(User.class);
List<User> users = RandomBuilder.aRandomListOf(User.class);
String anyString = RandomBuilder.aRandomString();

Whereas the BeanBuilder provides a fluent interface with finer control for building individual objects and graphs, for example;

User user = BeanBuilder.aRandomInstanceOf(User.class)
.excludeProperty("Id").build();
For this example i'm going to use the BeanBuilder so I can exclude the User.Id property from being populated by the random builder.

The Hamcrest-Bean Library

The hamcrest-bean library is an extension library to the Java Hamcrest library. The hamcrest-bean library provides a set of matchers specifically for testing Java objects and object graphs and performs deep inspections of those objects. It supports exclusions and overrides to allow fine control, if required, of how matching of any property, path, or type is handled, for example:

User expected = new User("Jane", "Doe");
assertThat(new User("John", "Doe"),
BeanMatchers.theSameAs(expected).excludeProperty("FirstName"));

A Sample Project

The sample project I'll work through is persistence of a simple User object with a child list of UserComment objects. This simple graph will be persisted to a H2 database with hibernate handling the Object-Relational Mapping (ORM) mapping, and Java Persistence Annotation (JPA) used to mark-up the model.

The Model

Below are the two model classes; first the User class.

package org.exparity.hamcrest.bean.sample.dao;

import java.util.*;
import javax.persistence.*;

@Entity
@Table
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  private Long id;
  private Date createTs;
  private String username, firstName, surname;
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  private List comments = new ArrayList<>();

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public Date getCreateTs() {
    return createTs;
  }

  public void setCreateTs(Date createTs) {
    this.createTs = createTs;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getSurname() {
    return surname;
  }

  public void setSurname(String surname) {
    this.surname = surname;
  }

  public List getComments() {
    return comments;
  }

  public void setComments(List comments) {
    this.comments = comments;
  }
}
Followed by the UserComment class.

package org.exparity.hamcrest.bean.sample.dao;

import java.util.Date;

import javax.persistence.*;

@Table
@Entity
public class UserComment {

  private Long id;
  private Date timestamp;
  @Transient
  private String text;
  private String title;

  public Date getTimestamp() {
    return timestamp;
  }

  public void setTimestamp(Date timestamp) {
    this.timestamp = timestamp;
  }

  public String getText() {
    return text;
  }

  public void setText(String text) {
    this.text = text;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }
}
Followed by the UserComment class.
package org.exparity.hamcrest.bean.sample.dao;

import java.util.Date;

import javax.persistence.*;

@Table
@Entity
public class UserComment {

  private Long id;
  private Date timestamp;
  @Transient
  private String text;
  private String title;

  public Date getTimestamp() {
    return timestamp;
  }

  public void setTimestamp(Date timestamp) {
    this.timestamp = timestamp;
  }

  public String getText() {
    return text;
  }

  public void setText(String text) {
    this.text = text;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }
}

The Data Access Object (DAO)

Next up we write our DAO layer. I've excluded the UserDAO interface from this post but it is available in the sample project ongithub .The full, if somewhat crude, implementation of the UserDAO is below.

package org.exparity.hamcrest.bean.sample.dao;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;

public class UserDAOHibernateImpl implements UserDAO {

  private final SessionFactory factory;

  public UserDAOHibernateImpl(final String resourceFile) {
    this.factory = new Configuration()
                .addAnnotatedClass(User.class)
                .addAnnotatedClass(UserComment.class)
                .buildSessionFactory(
                  new StandardServiceRegistryBuilder()
                    .loadProperties(resourceFile)
                    .build());
  }

  @Override
  public User save(final User user) {
    Session session = factory.getCurrentSession();
    Transaction txn = session.beginTransaction();
    try {
      session.save(user);
      txn.commit();
    } catch (final Exception e) {
      txn.rollback();
    }
    return user;
  }

  @Override
  public User getUserById(Long userId) {
    Session session = factory.getCurrentSession();
    Transaction txn = session.beginTransaction();
    try {
      return (User) session.get(User.class, userId);
    } finally {
      txn.rollback();
    }
  }
}

Integration Test

And finally, onto our integration test. The hibernate.properties will create an instance of an in-memory database and create the necessary tables on instantiation of the DAO.

hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:test
hibernate.current_session_context_class=thread
hibernate.cache.provider_class=org.hibernate.cache.internal.NoCacheProvider
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
The integration test is below.
package org.exparity.hamcrest.bean.sample.dao;

import static org.exparity.hamcrest.BeanMatchers.theSameBeanAs;
import static org.exparity.stub.bean.BeanBuilder.aRandomInstanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import org.junit.Test;

public class UserDAOHibernateImplTest {

  @Test
  public void canSaveAUser() {
    User user = aRandomInstanceOf(User.class).excludeProperty("Id").build();
    UserDAOHibernateImpl dao = new UserDAOHibernateImpl("hibernate.properties");
    User saved = dao.save(user);
    User loaded = dao.getUserById(saved.getId());
    assertThat(loaded, not(sameInstance(user)));
    assertThat(loaded, theSameBeanAs(user));
  }
}

Let's break the test down step by step to see what each step is doing and why the test is put together this way.

1) Model Setup

User user = aRandomInstanceOf(User.class).excludeProperty("Id").build();
Create a random instance of the User class and it's associates using exparity-stub. The instance will be populated with random data with the exception of the Id property. I've excluded the Id property so that is left null to test that the id is being generated in the database.

2) DAO Setup

UserDAOHibernateImpl dao = new UserDAOHibernateImpl("hibernate.properties")

Instantiate the DAO ready to be tested, passing in the property file to use for the test. The hibernate properties used will configure an in-memory instance of H2 and create the schema automatically.

3) Exercise the DAO

User saved = dao.save(user);
User loaded = dao.getUserById(saved.getId());

Save the random instance of the model set up in step (1) and then query the object back out again.

4) Verify the results

assertThat(loaded, not(sameInstance(user)));
assertThat(loaded, theSameBeanAs(user));

The first line verifies that the loaded User instance is not the same instance as the originally saved User. This prevents false positive results when the loaded instance is returned directly from a cache. The second line uses hamcrest-bean to perform a deep comparison of the loaded User instance against the original user instance.

Running the Test

The first run of the test yields an error; specifically a hibernate warning because a @Id annotation has been missed on UserComment.

org.hibernate.AnnotationException: No identifier specified for entity: org.exparity.hamcrest.bean.sample.dao.UserComment
  at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:277)
  at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:224)
  at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775)
  at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845)
  at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799)
  at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412)
  at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
  at org.exparity.hamcrest.bean.sample.dao.UserDAOHibernateImpl.(UserDAOHibernateImpl.java:15)
  at org.exparity.hamcrest.bean.sample.dao.UserDAOHibernateImplTest.canSaveAUser(UserDAOHibernateImplTest.java:18)

A fix to the UserComment object and we can run the test again.

@Table
@Entity
public class UserComment {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  private Long id;
  private Date timestamp;
  @Transient
  private String text;
  private String title;
  ...

After running the test again we get another failure. The presence of the @Transient annotation on the UserComment.text property is preventing the value being persisted

java.lang.AssertionError:
Expected: the same as 
     but: User.Comments[0].Text is null instead of "mDAWDJXbheIHbbHLR1NNVJqAki49RvaVwQtKD38r79u0y3MTDD"
  at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
  at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
  at org.exparity.hamcrest.bean.sample.dao.UserDAOHibernateImplTest.canSaveAUser(UserDAOHibernateImplTest.java:19)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:483)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)

Another change to the UserComment object to remove the @Transient annotation and we can run the test again.

@Table
@Entity
public class UserComment {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  private Long id;
  private Date timestamp;
  private String text;
  private String title;
  ...

After running the test again it all passes.

Try It Out

To try hamcrest-bean and exparity-stub out for yourself include the dependency in your maven pom or other dependency manager.

<dependency>
      <groupId>org.exparity</groupId>
      <artifactId>hamcrest-bean</artifactId>
      <version>1.0.10</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.exparity</groupId>
      <artifactId>exparity-stub</artifactId>
      <version>1.1.5</version>
      <scope>test</scope>
    </dependency>
Decentralized autonomous organization Persistence (computer science) integration test Object (computer science) Database Library

Opinions expressed by DZone contributors are their own.

Related

  • JSON-Based Serialized LOB Pattern
  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2
  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Using AUTHID Parameter in Oracle PL/SQL

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!