Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing hibernate daos with spring

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.

like image 928
Siva Avatar asked Sep 15 '11 10:09

Siva


2 Answers

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.

like image 70
Augusto Avatar answered Oct 20 '22 16:10

Augusto


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
}
like image 3
Ryan Stewart Avatar answered Oct 20 '22 16:10

Ryan Stewart