November 24, 2009

Testing Hibernate list() DAO method which fetches all records.

Consider the example where you have a static table "VERSION" and the DAO method that fetches all records from VERSION table through Hibernate.

DAO Method:

   public List getAll() {  
     Criteria crit = getSession().createCriteria(Version.class);  
     crit.addOrder(Order.asc("name"));  
     return crit.list();  
   }  

Poor Test case:
Many occasions I have noticed Test cases that directly assert on the number of records being returned.
 public class VersionDaoImplTest extends AbstractTransactionalJUnit4SpringContextTests{  
   @Autowired  
   private VersionDao versionDao;  
   @Test  
   public void shouldReturnTheListOfVersions() {  
     List versions = versionDao.getAll();  
     assertEquals(5, versions.size());  
   }  
 }  

As seen above, this test case tries to assert Only 5 records are there in the Version Table. When a new record is added to this table, this test case would fail.

Proper test case:
Other way of testing this method is given below.
 @Test  
   public void shouldReturnTheListOfVersions() {    
   List versions = ratingsDao.versionDao.getAll();  
     assertNotNull(ratings);  
     int prevSize = ratings.size();  
     String insertSQL = "Insert into VERSION (NAME,VERSION_NO) values (?,?)";  
     this.simpleJdbcTemplate.update(insertSQL, "TST+", 95);  
     this.simpleJdbcTemplate.update(insertSQL, "TST", 96);  
     this.simpleJdbcTemplate.update(insertSQL, "TST-", 97);  
     versions = versionDao.getAll();  
     assertEquals(prevSize + 3, ratings.size());  
   }  

In this test case, we get the number of records currently in the database. We then insert 3 new records into the table and try to assert whether the number of records being returned has increased by 3.

Testing Sort Order:
Also to test the Criteria.addOrder(Order.asc("name")) you can enhance the test case with the following:
 for (int i = 1; i < versions.size(); i++) {  
       assertTrue(versions.get(i - 1).getName().compareTo(versions.get(i).getName()) < 0);  
 }  
This would assert that records are sorted by the NAME.

2 comments:

  1. Arthur Ronald F D GarciaMarch 24, 2012 at 10:31 AM

    Nice solution. Congratulations!

    ReplyDelete
  2. Hi Venkatesh,
    I dont understand waht you are doing here. Can you help me with the "proper" example. What is "ratings" and "ratingsDao" in this example. How is it related to "versions"?

    ReplyDelete