Siva
Siva

Reputation: 1367

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.

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.

Upvotes: 8

Views: 6102

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128759

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
}

Upvotes: 3

Augusto
Augusto

Reputation: 29827

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.

Upvotes: 5

Related Questions