I’m interested to know what approach people are taking in developing automated unit tests that exercise the database
Do you Install a QA database (known-starting point) before the test suite is run.
OR
Do you build database stub that stand-in whenever a database call occurs?
EDIT: Related question, but not a duplicate, though quite important for the matter at hand: How do I unit-test persistence?
The ‘database stub’ that stands in is usually referred to as a ‘fake repository’ or ‘mock repository’. They are a good idea. You can code them by hand (not hard for simple cases) or use a framework like Rhino Mocks to generate them. You don’t mention what language you are working in. Rhino mocks is for .Net .
If you use mock repositories then you can run tests against code that works with data, without actually using a database for the data. This makes the tests run very fast, which is a good thing.
Of course, you still have to test the real repository at some stage, and this is more of an issue. These tests will run slower, because they use a real database. Some would classify then as ‘integration tests’ not unit tests because of the speed and dependency issues.
I don’t mind what you call them so much, but it’s a good idea to keep these tests separate.
A good idea here for data consistency is to begin a db transaction before your test, and roll it back afterwards. That way the database state is reverted to what it was before the test.