Jerome Cance
Jerome Cance

Reputation: 8183

Should I use mock or dbunit to test a method which access to a database?

I've got a method which does some calls to a database using some DAO.

Should I use mock mechanism to avoid managing a database (and so mock all DAO methods) or should I use dbunit (or some equivalent) to test by loading and init a database in memory (like hsqldb) ?

Are these any pros and cons for each method (mock vs dbunit) ?

Upvotes: 1

Views: 2067

Answers (3)

CloudyMarble
CloudyMarble

Reputation: 37566

I would recommend using mock obejcts, in general Database access is not really performant and costs much time, we had a project with over 4000 unit tests, it took more than 3 hours to run the complete tests, specially when consider that the setup and tear down access the database before and after each test.

regarding dbunit I used it so I can not really say if its good or not, but as said i would avoid database access in a unit test, it should be limited to the logic units only.

Upvotes: 1

duffymo
duffymo

Reputation: 308813

You want to test the database. I don't see how mock makes sense in this context. Once you know the DAOs are working, then injecting mocks into services that uses them fits.

In the meantime, do test your database. You can either create a temporary test database or make all your tests transactional: set up the test unit of work, execute it, validate it, roll it back.

Upvotes: 2

cjstehno
cjstehno

Reputation: 13994

It's a tough question to answer definitively; however, what I would suggest and what I have generally preferred, is to test the DAO itself against an embedded database or an external test database (as an integration test) so that you know your DAO functions properly against a read database of some sort.

Then for components that use the DAO, you can mock it to decouple your tests from having to use a database explicitly.

The cons for this approach are that you have to have some sort of embedded or other DB available for testing.

You can mock your DAO unit tests; however, you are then not entirely sure that your mocking is going to be a true representation of what the DB will provide.

Hope this helps.

Upvotes: 0

Related Questions