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.
Nice solution. Congratulations!
ReplyDeleteHi Venkatesh,
ReplyDeleteI 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شركة نقل عفش من الرياض الى جدة
شركة نقل عفش من الرياض الى الامارات شركة شحن عفش من الرياض الى الامارات
شركة نقل عفش من الرياض الى الاردن شركة شحن عفش من الرياض الى الاردن
شركة نقل عفش من الرياض الى الدمام