views:

51

answers:

3
+2  Q: 

unit testing DAOs

Let's say I'm doing unit testing methods for a UserDAO. I'm writing the test for the UserDao's deletion method. I would first insert a user into the db, then call the deletion method, and verify if the object still exists.

My question is: for the deletion unit test, when I'm inserting a user to test, should I be calling the UserDao's insertion method...OR would it be better not to call any methods of the object that I'm testing and use the native way, say using jdbc to do the insertion, and then call my deletion method?

A: 

In Simple words, you shd only do this if you want a real test

Use Mocking

this concept is designed to help unit testing without actual object used.

you can mock your database object here and even if there is no database exist.

but if you need to test the actual deletion , than you shold use you DAO's method like Insert using your DAO and then delete using your DAO.

It will let you test both of the Unit test cases simulteneously.

saurabh
I don't think we should be mocking database objects when we are testing DAOs(Data Access Objects), though. If we are mocking the DAOs, then what would the value of the test be? Things that should be mocked imho would be DAOs. If we are testing a class that uses a DAO in a method, the DAO should be mocked. Also, I don't think we shoudl be testing two methods in one unit test like you've suggested
Glide
A: 

DAOs are often too simple to break, then I think it is not worth to spend resources on testing. Your explanation looks like this is the case.

Only if there is some logic involved (building more complex queries together) I would think of testing some parts.

Maybe provide some code snippets to help out more.

manuel aldana
+1  A: 

Use DBUnit or something similar to set up the data for the test. DBUnit lets you specify what test data gets inserted for a test, you can even specify a clean insert that deletes everything (from the tables that have test data specified for them), then inserts only what you want. It's best if tests are independent of each other, you don't want a problem with the insert code to cause problems for other tests that depend on it for setup.

Nathan Hughes
I will definitely check that out, but I guess the answer doesn't answer my question. I guess without using DBUnit, how would you answer my question.
Glide
Without DBUnit, I would still want to have a way to clean the database and set up data before each test, so that they have an explicit start state and are not order-dependent. That means I would still want to avoid using a dao to insert data, because it's not as explicit.
Nathan Hughes