I have a DAO service which retrieves and saves data to Hibernate. Could anybody point me to testing Methodology using JUnit for such service.
What is the best practice? When should I have passed test failed test and should I test exc开发者_开发百科eption?
You should test every possible path in your DAO. You would definitely use an in-memory database for your tests, such as HSQLDB
.
One strategy would be to give the database some initial data in your setUp()
method and clean it up on tearDown()
, so all tests have a consistent working environment.
With these setup you can basically do everything... For example, if you want to test a save()
method in your DAO, just add the new element and make sure that your table now has one more element. Moreover, fetch that element and compare it to the one you've inserted, it should obviously be the same.
Remember that you should always test every possible path.
I would also look into using DBUnit to ensure that your database is consistent and test independent. They have articles on how to get started and a tutorial. There a quite a few articles on IBM's DeveloperWorks blog as well that you might want to read.
I think using an in-memory database is often a good idea - for unit test. But the ideal is to combine fast unit tests with such a database with integration tests hitting the real database. There are subtle differences between, e.g., Hypersonic SQL and most production servers.
Consider using mocks for testing your error handling (i.e. mock the Hibernate session object and make it throw exceptions for certain operations)
精彩评论