Ciro Anacleto
Ciro Anacleto

Reputation: 119

How to test the persistence layer?

I am developing a web project multi-layer and multi-modules. For the persistence layer I'm using JPA 2.1 and Hibernate 4.2 and for the tests JUnit 4. In this architecture my project was divided on the following classes:

GenericDAO (interface);
GenericDAOImpl (implementation);
EntityDAOImpl (inherits from GenericDAOImpl);
GenericService (interface);
GenericServiceImpl (implementation);
EntityServiceImpl (inherits from GenericServiceImpl);
Entity (POJO).

A entity could be any object: user, account, city, country ...

Naturally, this entities have dependencies each other and mapping one-to-one, one-to-many, many-to-one e many-to-many. I would like testing whether such entities are being persisted, with their relationships, correctly on database.

I started developing tests using a in memory database (HSQLDB) provided by spring. I created a generic class test, GenericServiceTest, that test my class methods GenericServicesImpl and extended for each specific entity, for example EntityServiceTest.

Then when you run the test class EntityServiceTest all JUnit methods and annotations located in GenericServiceTest class are inherit and the test to this specific entity is performed.

For to simulate the objects I used fixture objects (fake objects). However, I am having a considerable work to test the persistence between entities precisely because of such relationships. Problems like: not-null attributes (fields) that must be recovered of database before save the object whitch depends him.

My doubts are:

I appreciate some help!

Upvotes: 3

Views: 2322

Answers (1)

Crazyjavahacking
Crazyjavahacking

Reputation: 9677

From my perspective you are focusing on a wrong thing.

I would like testing whether such entities are being persisted, with their relationships, correctly on database.

This looks like testing whether JPA implementation (Hibernate in this case) is implemented correctly. Testing persistence itself does not make that much sense as in that case you are testing an external system rather than your code.

If you need to really really test the persistence, you should use the following scenarios:

@Test
public void persistingUser_ShouldWorkCorrectly() {
    // arrange
    User user = createUser();

    // act
    userDAO.save(user);

    // assert
    assertThat(user).hasName(...)
                    .livesInCity(...)
                    .livesInCountry(...);
}

Upvotes: 2

Related Questions