The T-Files


Sun, 08 Jan 2006

The thousand and one reasons to love Perl: [17] DBD::Mock

I am the maintainer for a Perl database abstraction module, that automatically creates the necessary SQL to access stored procedures. Testing code that interacts with a database can be tricky. You need to have instances of all the supported database products available. You need to set up the connection passwords for the test suite. Certain tests may depend on the database being in a certain state, so you need to put it in that state. Basically you want to have complete control over the database for the purpose of running your tests without risking to damage any important data that may be stored in there. And of course, the tests should still be able to run automated, for example as part of the CPAN install process.

Enter DBD::Mock. It is a fake database driver that just accepts and records all the commands you throw at it. You can also prep it with mock data that it should return. After running a transaction using DBD::Mock (instead of the regular database driver), you can check the logs it collects and verify that the SQL your code has issued came out as expected. Obviously, you cannot check how a real database would have reacted to it, but testing the database is not your job anyway: You should only really be concerned that your SQL is correct (which you have to verify in some other way). There are certainly cases where you need to do the whole real-world round-trip, but for an SQL-generating module such as mine, DBD::Mock already takes you a long way.