#!/usr/bin/env perl use strict; use warnings; use diagnostics; use Readonly; use Test::MockDBI; use Test::Simple tests => 10; use DbLibTry; # Testing DbLibTry Perl module Readonly my %RET_VALS => ( 1 => { name => 'fgv3df1fv5f3', time => '32:20', album => 5120, order => 2, }, 2 => { name => 'fdgetre14w6e46we4', time => '2:00', album => 89, order => 5, }, ); my $dblibtry = DbLibTry->new; my $mock_dbi = Test::MockDBI::get_instance; my %song; $mock_dbi->set_retval( method => 'get_all_songs', retval => \%RET_VALS ); ok(defined $dblibtry, "Defined $dblibtry"); ok($dblibtry->isa('DbLibTry'), 'ISA'); ok($dblibtry->can('connect'), 'Method ->connect() exists'); ok($dblibtry->can('disconnect'), 'Method ->disconnect() exists'); ok($dblibtry->can('get_all_songs'), 'Method ->get_all_songs() exists'); ok($dblibtry->connect == 1, 'Connected'); ok(%song = %{$dblibtry->get_all_songs}); ok($dblibtry->disconnect == 1, 'Disconnected'); ok($song{2}->{order} == 2); ok($song{1}->{time} eq '2:00'); #### package DbLibTry; use strict; use warnings; use diagnostics; use DBI; sub new { return bless {}, shift; } sub connect { my $self = shift; $self->{dbh} = DBI->connect( "DBI:SQLite:dbname=songdb.sqlite3", q{}, q{}, {RaiseError => 1} ) or return $DBI::errstr; return 1; } sub disconnect { my $self = shift; $self->{dbh}->disconnect; return 1; } sub get_all_songs { my $self = shift; my $sth = $self->{dbh}->prepare('select * from songs;'); my $rv = $sth->execute or return $DBI::errstr; return $DBI::errstr if ($rv < 0); my %hash; while (my @row = $sth->fetchrow_array) { $hash{$row[0]} = { name => $row[1], # Name of song time => $row[2], # Total time of song album => $row[3], # Album ID for song order => $row[4], # Order of song in album }; } return \%hash; } 1; #### #!/usr/bin/env perl use strict; use warnings; use diagnostics; use feature qw(say); use Data::Dumper; use DbLibTry; my $dblibtry = DbLibTry->new; $dblibtry->connect; my %hash = %{$dblibtry->get_all_songs}; $dblibtry->disconnect; say Dumper %hash; #### $ perl dblibtry.t 1..10 ok 1 - Defined DbLibTry=HASH(0x8847860) ok 2 - ISA ok 3 - Method ->connect() exists ok 4 - Method ->disconnect() exists ok 5 - Method ->get_all_songs() exists ok 6 - Connected Can't use an undefined value as a HASH reference at dblibtry.t line 46 (#1) (F) A value used as either a hard reference or a symbolic reference must be a defined value. This helps to delurk some insidious errors. Uncaught exception from user code: Can't use an undefined value as a HASH reference at dblibtry.t line 46. # Looks like you planned 10 tests but ran 6. # Looks like your test exited with 255 just after 6. $