Akka Jaworek
Akka Jaworek

Reputation: 2120

Testing HQL with Junit

How can I test HQL query with JUnit tests?

I have mapped Entity Class:

@Entity
@Table(name = "DOE")
public DomainObjectEntity {
    //some attributes
}

which represents domain objects:

public class DomainObject {
     //some attributes
}

I also have repository interface for my domain objects:

 public interface DomainObjectRepository {

     /**
     * Gets entity by some attribute
     * 
     */
     DomainObject getDomainObjectByObjectId(String objectId);
}

this interface is implemented in

 @Repository
 public class DomainObjectRepositoryImpl implements DomainObjectRepository {

     @Inject
     private DomainObjectEntityJPARepository entityRepository;

    @Override
     public DomainObjectgetDomainObjectById(String parcelId) {
        //this converts my entity to domain object
        return entityRepository.findByDomainObjectId(DomainObjectId.getStr()).getDomainObject(); 
    }

}

my JPA Entity repository looks like this:

public interface DomainObjectEntityJPARepository extends  JpaRepository<DomainObjectEntity, String> {
    /**
     * get DomainObject with requested id
     * 
     * @param objectId - objects id
     * @return DomainObject
     */
    @Query("some query to be tested")
    DomainObjectEntity findByDomainObjectId(@Param("objectId") String objectId);
}

and finally i want to write a simple JUnit test to check if query to findByDomainObjectId returns the correct object. I think my test should look like this:

  1. create object to put into DB
  2. retrieve object from DB
  3. compare objects

How can I write such test?

Any good examples of testing HQL query with junit and repositories?

Upvotes: 0

Views: 1561

Answers (2)

muru
muru

Reputation: 61

You just have to use a test db, like H2 which is a in memory db, and then use Junit to see the returned entity.

Upvotes: 0

LuckAss
LuckAss

Reputation: 114

if you want to test, if your method returns the correct object, just mock your entitymanager or whatever you use for querying your DB using mockito.

If you want to test if your query works, you should setup a test DB (a in memory DB is used in this case most of the time) with the same schema and simple test data already in the DB. In your test method you should only call the method with a known id and check if you get the correct object. H2 is simple to use for in-memory testing and you can use your create.sql script (if you have one) and an insert.sql script, where you define your known test data.

It is an important aspect of unit testing to only test one part of your program at a time. if you would insert into the DB in your test you would also test the insert aspect and not only the read aspect.

Upvotes: 1

Related Questions