We are currently writing unit test cases in our project . The implementations for database methods exist and is working fine . In this case why do we need to write mock objects ? Is there any specific reason ? Why can't I test the DAO implemntation directly?
You shouldn't mock calls to the database because that would defeat the purpose. What you SHOULD mock are, for example, calls to your DAO from, say, a service layer. Mocking allows you to test methods in isolation.
Say you have a restaurant simulation with an architecture like this:
Cook <=> Server <=> Customer
You want to test each layer independently. Here the
Server is your service layer and the
Cook can be thought of as a DAO. The
Server is what you want to mock while testing
Customer, and the
Cook is what you want to mock while testing the
Cook unit tests, however, should verify that the implementation is returning a hamburger when a hamburger was ordered and not a rubber tire.
It is perfectly ok to test businesslogic together with the database. but these tests are called integration tests even if you use nunit or junit or phpunit to execute these.
Unittests are spezialized tests where testing in isolation (i.e. buisinesslogic without the database) is important. Mocks/fakes/stups are used to enforce this isolation.
Another reason is to avoid the execution time of actually running the database commands. It may not seem like much but the overhead of setting up and tearing down connections will eventually add up and most likely significantly increase the overall time to run the test suite compared with using mock objects.
Simply: to test actual DAO and not database content.
Suppose your DAO Person class has a method getByName(). You write a test and call Person.getByName("John Smith"). Suppose the test fails, because somebody removed John's record from database. Now, every CI software and your supervisors/reviewers can claim that your software is faulty, while in reality it is not. If you mock DB, you can prove that your DAO works if it's given correct row from correct table.
If you really want to test database itself, ie: if execution of certain DAO method puts data in a certain state, then it is also possible. What is more it is really helpfull with wacky data models (EAV, nested tree set) where you can't expect database to provide bullet-proof integrity. Have a look at DBUnit to make your life easier.
To isolate the class you are testing. Or else if the test fails how do you know the problem is in the class you are testing or one of it's dependencies.