Mocking vs. Test DB?

Ray picture Ray · Nov 21, 2008 · Viewed 10.3k times · Source

Earlier I asked this question How to correctly unit test my DAL?, one thing left unanswered for me is if to really test my DAL is to have a Test DB, then what is the role of mocking vs. a testing DB?

To add on this, another person suggested to "use transactions and rollback at the end of the unit test, so the db is clean", test db that is. What do you guys think of this testing + test DB + transaction rollback (so db is not really written) approach to test DAL?

To be complete, my DAL is built with Entity Framework, there is no stored proc in DB. Since EF is so new, I really need to test DAL to make sure they work correctly.

Answer

tvanfosson picture tvanfosson · Nov 21, 2008

I think you'll probably want to do some integration testing to check logic that is enforced by your database structure, for example constraints, triggers, autoincrement columns, etc. You should, however, for unit testing mock out whatever framework components that your DAL relies upon as you want (in your unit tests) to test only those components that you have coded. You don't really need to test methods on SqlCommand or SqlConnection (for example). You should assume that the framework components that you use work and create stubs or mocks for them that return known data (good, bad, exceptions) to your methods to make sure that your methods work properly. Without mocking you are responsible for generating the data in the database and making sure that it is correct. You also leave open dependencies on the network, the database itself, etc. that may make your tests brittle.

Also, unit testing does not remove the need for other types of testing. Integration tests and acceptance tests are still valid and need to be done. They probably don't need to be done with the same frequency as unit tests and may not need to be as extensive as your code quality improves with unit testing, but unit testing is not a magic bullet.