Reputation: 1007
Our application has a service layer and a DAO layer, written as Spring beans.
While testing the Service Layer- I do not want to depend upon a real database so I am mocking that by creating a 'Mock' Impl for the DAO layer
So when I am testing the Service layer- I chain the Service layer beans to the Mock DAO beans And in Production- will chain the Service layer to the 'real' DAO beans
Is that a good idea ? Any alternate suggestion on how to mock the database layer ?
Clarification:This question is about testing the Service Layer and not the DAO layer. While testing the service layer- I assume that either the DAO layer has already been tested or doesn't need testing. The main thing is- how do we test service layer- without being dependent upon the DAO implementation- hence I am mocking the DAO layer
Upvotes: 7
Views: 6823
Reputation: 83081
As I understand the question it is explicitly dedicated to best practices regarding testing DAO layers, as mocking a database seems nnot so straightforward as mocking the DAO layer when testing services.
Personally I'd raise the question back if it's reasonable to really unit test a DAO layer in the classical unit testing meaning. If you design your DAO layer properly it does not do much more than mapping domain objects to queries.
That said I alway propose to use an embedded database like H2, HSQL or the Java 6 embedded Derby to do things like this as mocking a datasource is really much more effort than simply raising an embedded database. Spring 3 will provide a nice builder pattern to create such databases on the fly. RC1 of it will also introduce a jdbc
namespace to ease setup further. See this one for details.
But even with current Spring 2.5 branch using an embedded database is just a matter of taking the databases JAR and setting up a DataSource
accordingly.
Upvotes: 0
Reputation: 8582
You are definitely on the right track.
My mocking framework of choice is Mockito
Upvotes: 1
Reputation: 196
This is a technique we've been using for many years now. Note that when it comes to mocking the DAO interfaces you have some choices:
Dynamic mocking frameworks allow you to stub out a variety of circumstances (no data, 1 row, many rows, exception throwing) without having to create complex classes to stub out the behavior you wish to test
Upvotes: 5
Reputation: 39480
That's a great way to use mocking to test the database. I don't think any alternative suggestion is necessary; I think you've got the right technique already!
Upvotes: 1