Reputation: 41
I am trying to unit test my DAOs, but i'm having some trouble.
First off, my DAO has 1 method: a findById
type method. i want to write a unit test for this. so, my line of thinking is:
findById()
on the DAO, Now, the part i'm having a hard time with is trying to figure out how to do the insert.
My concerns:
I currently don't have an insert
method in my DAO. I could write one, but i don't see the point in doing it simply for the sake of testing.
The other possibility is to use the Hibernate API (ie HibernateTemplate) to perform the insert. But, i want my unit tests to be flexible. I don't want to tie my unit tests to any specific API.
What should i do?
Upvotes: 2
Views: 1502
Reputation: 17518
You can try using Spring's support for embedded databases when configuring the spring context of your integration test. The <jdbc:script>
tag allows you to execute init and destroy scripts:
<jdbc:embedded-database type="H2" id="dataSource">
<jdbc:script execution="INIT" location="setup.sql"/>
<jdbc:script execution="DESTROY" location="teardown.sql"/>
</jdbc:embedded-database>
Upvotes: 1
Reputation: 10987
Generally I do not write unit tests for my DAOs. I prefer to test this area via integration/functional testing.
If you want to then one option is to pre-populate the database so your unit test case know what to expect from the database.
Spring provides excellent DAO layer test framework where the data changes are rolled back so that one test does not impact other due to data change.
Upvotes: 1
Reputation: 13821
Depending on your database (i prefer an in-memory variant for testing), you should be able to pre-populate the database and set it to a known state before each individual test. So there's no need for an insert
method just to do testing. I have used HSQLDB (which is now superseeded by another database which I don't remember the name of right now) for this many times, and I usually create the database and run some insert SQL statements to populate the database before each test. There are also frameworks for this, like DbUnit.
Edit
The database I was thinking of was H2. It seems like it also has a neat feature that it can execute a script when a connection is made
String url = "jdbc:h2:mem;INIT=runscript from '~/create.sql'\\;runscript from '~/populate.sql'";
Upvotes: 2