$dbh = DBI->connect('..', '..', '..');
$sth = $dbh->prepare(q{select ..});
if ($sth && !$sth->errstr()) {
while (my $row = $sth->fetchrow_arrayref()) {
..
}
}
####
no strict 'refs';
*{ Test::MockDBI::errstr } = sub { return };
####
package db;
# db.pm
use strict;
use warnings;
use Data::Dumper;
use DBI;
our $dbh = undef;
sub connect {
$dbh = DBI->connect('DBI:mysql:test', '', '')
or die "connect failed";
}
sub disconnect {
$dbh->disconnect();
}
sub select_i_from_t {
my $sth = $dbh->prepare(q{select i from t}) or die "prepare failed";
$sth->execute() or die "execute failed";
my $arref = [];
if ($sth && !$sth->errstr()) { # <-- errstr is always be false in
# <-- Mocked mode
while (my $row = $sth->fetchrow_arrayref()) {
push @$arref, $row->[0];
}
} else {
die "no sth" if (!$sth);
die "errstr:" . $sth->errstr() if ($sth->errstr());
}
return $arref;
}
1;
__END__
# db.t
use strict;
use warnings;
# Signal the we want to use Test::MockDBI
BEGIN { push @ARGV, "--dbitest=42"; }
use Data::Dumper;
use Test::More;
use Test::MockDBI;
BEGIN { plan tests => 4 }
use_ok(q{db});
my $mock_dbi = Test::MockDBI::get_instance();
# Replace the code for sub errstr in Test::MockDBI.
# Code is from Test::MockObject (CPAN)
{
## no critic (ProhibitNoStrict)
no warnings 'redefine';
no strict 'refs';
*{ Test::MockDBI::errstr } = sub { return };
}
my $vals = [ [123], [124], [125] ];
$mock_dbi->set_retval_scalar(
42,
"select i from t",
sub { shift @$vals }
);
ok(defined(db::connect()), q{Expect connect() to return true});
is_deeply(
db::select_i_from_t(),
[ 123, 124, 125 ],
q{Expect select_i_from_t() to return arrayref [ 123, 124, 125 ]}
);
ok(defined(db::disconnect()), q{Expect disconnect() to return true});
__END__
####
$ prove db.t
db....Name "Test::MockDBI::errstr" used only once: possible typo at db.t line 24.
db....ok 2/4errstr:DBI error at 'select i from t' at db.pm line 32.
# Looks like you planned 4 tests but only ran 2.
# Looks like your test died just after 2.
db....dubious
Test returned status 255 (wstat 65280, 0xff00)
DIED. FAILED tests 3-4
Failed 2/4 tests, 50.00% okay
Failed Test Stat Wstat Total Fail Failed List of Failed
-------------------------------------------------------------------------------
db.t 255 65280 4 4 100.00% 3-4
Failed 1/1 test scripts, 0.00% okay. 2/4 subtests failed, 50.00% okay.