Reputation: 1391
I want to use JUnit to test Hibernate code such as insert, update, delete,.. method and transaction management.
But I don't know how to apply unit test for Hibernate usefully and what should I test with Hibernate.
How can I test DAO methods?
Hope that you could give me some guides!
Upvotes: 6
Views: 7576
Reputation: 10163
If you've created a DAO object, you can then send it some objects, call save, and then retrieve those objects and test the field values. That's very basic Hibernate testing.
Make sure you clean up your data though in your setup or teardown methods. If you save objects, delete them.
Best practices from Rails are to use a separate database for testing, one populated with test data. I wouldn't do this against a production database; if you have a development database for yourself that you can easily repopulate with data, just use that.
Upvotes: 0
Reputation: 33783
I use Chris Richardson's approach, described in POJO's in Action book
In-memory SQL database
Pros
Cons
Named queries
Pros
Cons
Mock repositories
Pros
Cons
DBUnit
Pros
Cons
regards,
Upvotes: 2
Reputation:
Personally I'm very wary about using embedded databases like HSQLDB with Hibernate and expecting that everything will work exactly the same when you move it to Oracle/MySQL/SQL server. Hibernate is too leaky an abstraction for that.
I have no experience with other frameworks besides JUnit. I find it does the job pretty well. Here's some things I always bear in mind:
Upvotes: 0
Reputation: 72998
OK, a few points.
First of all, if you must test actual code that talks to the DB, use DBUnit for making your life easier, and it is recommended that you use HSQLDB, so that your tests will be able to setup their environment on runtime, without requiring a database already being installed and configured.
Second, if you don't have to talk with the DB, I'd use a general mocking library (be it EasyMock, JMock or Mockito, for example), and make the tests not really talk to a DB, which will usually make tests faster and simpler.
Upvotes: 0
Reputation: 3509
You can use DBUnit to test DAO Layer. Because you need data to test.
Example : DBUnit xml will insert dummy data to database which is described by you and then you can call assertEquals("myname", userDAO.findById(1).getName()); etc. After test you can delete dummy data with DBUnit. Check detail.
Documents
Hibernate testing with dbunit
DBUnit and Hibernate
Upvotes: 4
Reputation: 597362
You can use a number of approaches, depending on your scenario
@Before
, and delete in @After
. This is, however, not exactly a "unit" test, because it depends on some external preconditions.Upvotes: 2