I have a database-backed application which, sadly, has very few tests of its database. I’m trying to get up to speed on effectively testing the database.
So far, I’ve learned:
- test the ability of the application to put/fetch data to the database
- use mock DB’s to test object/relation-mapping code
I’m still struggling to implement the first point. It seems that the only way to test that is to insert data into the real tables. But of course the user won’t want to see my test data. Here’s what I’m currently doing in pseudo-code:
begin a transaction
insert a few rows
check that no error has occurred
'select' the rows back out
check that no error has occurred, check that data out matches data in
tell the test framework that it's successful
abort the transaction
Is this a best practice, or some kind of horrible anti-pattern? Any better suggestions?
Your user definitely shouldn’t see your test data, because testing in production is really bad practice! You should try to create a test environment and do your testing there.
One solution I’ve found to work is to create a separate database instance, populate it with some known data, and use that for your integration testing. Be sure to clean up your database after each test case, as test cases should be independent.
Using transactions in the test database is not such a bad practice, since you can confirm things and then rollback the transaction, but I would be concerned that you’re going to call code that will commit to the database, thereby changing the parameters for following tests. Of course, if your DB supports nested transactions, this isn’t a big deal, but ISTM that not all DBs do that.