I have a small experience with JUnit and TestNG, and today I need to do some Unit Testing for Java database code.
I really don’t know how I can achieve this. because I think it’s more difficult to test databases than normal code.
Is there any clues you can give me ?
Thanks.
EDIT
What do you think about DbUnit
You can get started with DbUnit.
By the way, you do not test databases when you unit test the classes accessing the database. You ought to be putting the database in a known state before and after your tests, and you ought to verify that your classes have fulfilled their contracts.
Your following was more specific about DbUnit:
DbUnit has been around for quite sometime. As far as plain DAO (Data Access Object) implementations are concerned (assuming that you are following the DAO pattern), DbUnit is a good fit, as you can setup the state of the database before testing the DAO, then execute the test against the DAO classes and verify that the expected operation completed successfully. Like other JUnit tests, you can also expect exceptions thrown by the DAO, if the contract of the DAO specifies that exceptions would be thrown, for instance, in cases where data is not found.
Do keep in mind that there is nothing spectacular about testing against a database. You ought to focus on testing your classes instead of testing the database. In simpler words, a database (and the JDBC driver) ought to be seen as collaborators for your SUT (System-Under-Test) and not as the SUT. It is your DAO classes and their contracts that ought to be tested.