I like to write JUnits for my hibernate dao implementations and seek opinion on the suggested approach for writing these unit testcases. I can think of two strategies.
Mocking hibernate template using a library like EasyMock and testing just the DAO implementation against these mock objects. (Not really satisfying as I would be testing against a mock layer and not really against test data)
Testing against a real test database (an in-memory/external) by writing some test data before running my unit test.
Which approach is a good way of ensuring our DAOs are properly tested. Please point me to any examples on configuring tests using the second approach. I tried looking around but haven't found the right ones.
Thanks, Siva.
I would follow the second way, using HSQLDB as the DB engine. I think that invoking the real implementation behind a DAO has the positive effect of catching mapping errors.
If your DAOs have more logic that it's not related to deal with hibernate (imagine if you DAO loads some objects and then performs some operations on them to return a different object), I would create a different test class to test the methods with extra logic, and mock the methods that return the data. This allows you to set up the data in an easier way rather than priming the DB and immediately loading those objects.
Test against a real database. Most of the complexity of Hibernate is in the mapping, and if you mock the SessionFactory (or what encapsulates it), you miss testing that entirely. Use the Spring Test Framework, to greatly ease your testing, and for local, "unit" tests, test against an in-memory database. H2 is simple to use and very fast (better than HSQLDB or Derby). E.g.:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("your test context.xml")
public class FooDaoTest {
@Autowired
private FooDao dao;
@Transactional
public void saveFoo_succeeds() {
// test save
}
@Transactional
public void saveAndLoadFoo_resultsInSameFieldValues() {
// save and load; compare fields from before to after
}
// test custom queries
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With