O'Reilly logo

Perl Testing: A Developer's Notebook by Chromatic, Ian Langworth

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mocking Databases

Any serious code that interacts with external libraries or programs has to deal with errors. In the case of database code, this is even more important. What happens when the database goes away? If your program crashes, you could lose valuable data.

Because error checking is so important, it’s well worth testing. Yet none of the techniques shown so far make it easy to simulate database failures. Fortunately, there’s one more trick: mock your database.

How do I do that?

InsertWrapper is a simple module that logs database connections and inserts, perhaps for diagnostics or an audit trail while developing. If it cannot connect to a database—or if the database connection goes away mysteriously—it cannot do its work, so it throws exceptions for the invoking code to handle.

Save the following example in your library directory as InsertWrapper.pm:

 package InsertWrapper; use strict; use warnings; use DBI; sub new { my ($class, %args) = @_; my $dbh = DBI->connect( @args{qw( dsn user password )}, { RaiseError => 1, PrintError => 0 } ); my $self = bless { dbh => $dbh, logfh => $args{logfh} }, $class; $self->log( 'CONNECT', dsn => $args{dsn} ); return $self; } sub dbh { my $self = shift; return $self->{dbh}; } sub log { my ($self, $type, %args) = @_; my $logfh = $self->{logfh}; printf {$logfh} "[%s] %s\n", scalar( localtime() ), $type; while (my ($column, $value) = each %args) { printf {$logfh} "\t%s => %s\n", $column, $value; } } sub insert { my ($self, $table, %args) = @_; my ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required