Catalyst/DBIx::Class and DBD::Mock
I was writing unit tests for a Catalyst-based Perl application today, and, this being my first big application using DBIx::Class, I had no idea how to mock the database layer. I searched the web, to no avail, which leads me to this blog entry: here's how you mock your Catalyst model from a unit test script.
First, you don't have a $c object when you're in a unit test, but it turns out you don't really need it. You also don't need your DB class, which works out nicely. You do, however, need DBD::Mock, as a replacement for your usual DBD package, and, of course, you need to have your result sets in your Perl include path.
Let's say our application is called MyApp, following the convention of the Catalyst documentation.
Now it's easy enough to get a schema object.
my $schema = MyApp::Schema->connect('dbi:Mock:', q{}, q{});
Before you perform any queries, you need to seed that mock DBD with some data. Which means you need access to the DBI object.
my $dbh = $schema->storage->dbh;
Easy, right? Now, let's add some data to the underlying DBD.
my @data =
(
[ qw(column1 column2) ],
[ qw(foo bar) ],
);
$dbh->{mock_add_resultset} = \@data;
This gives the DBD a table with two columns, column1 and column2, and one row containing values "foo" and "bar", respectively.
You're ready to go! Use your schema and result sets as you usually would.
