Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing tests for DAOs

I'm currently assigned to write a test for a project, is it necessary to write tests for DAO classes?

like image 788
London Avatar asked May 25 '10 08:05

London


1 Answers

It depends :-)

If your DAO classes contain only the code needed to fetch entities from the DB, it is better to test them in separate integration tests*. The code to be unit tested is the "business logic" which you can unit test using mock DAOs.

[Update] E.g. with EasyMock you can easily set up a mock for a specific class (with its class extension, even concrete classes can be mocked), configure it to return a specific object from a certain method call, and inject it into your class to be tested.

The EasyMock website seems to be down right now, hopefully it will come back soon - then you can check the documentation, which is IMHO quite clean and thorough, with lots of code examples. Without much details in your question, I can't give a more concrete answer. [/Update]

If, OTOH, the DAOs contain also business logic, your best choice - if you can do that - would be to refactor them and move the business logic out of DAOs, then you can apply the previous strategy.

But the bottom line is, always keep in mind the unit testing motto "test everything which could possibly break". In other words, we need to prioritize our tasks and concentrate our efforts on writing the tests which provide the most benefit with the least effort. Write unit tests for the most critical, most bug-risky code parts first. Code which - in your view - is so simple it can't possibly break is further down the list. Of course it is advisable to consult with experienced developers on concrete pieces of code - they may know and notice possible traps and problems you aren't aware of.

* unit tests are supposed to be lightweight, fast and isolated from the environment as much as possible. Therefore tests which include calls to a real DB are not unit tests but integration tests. Even though technically they can be built and executed with JUnit (and e.g. DbUnit), they are much more complex and orders of magnitude slower than genuine unit tests. Sometimes this makes them unsuitable to be executed after every small code change, as regular unit tests could (and often should) be used.

like image 128
Péter Török Avatar answered Oct 06 '22 19:10

Péter Török