[prev UnitTestingMyLibraryPrintHeader | next UnitTestingMyLibraryReturnError | top UnitTestingMyLibrary ]
The next subroutine for testing presents some new wrinkles.
sub gracefulExit {
# print the footer
&printFooter;
# close the html
print $output->end_html;
# disconnect the handle to the database
if ($gSth) { $gSth->finish; }
$gDBhandle->disconnect;
# quit gracefully
exit;
}
One problem is the exit statement here. If you call this subroutine from a TestSuite, it stops execution of the TestRunner. This makes it necessary to go into the copy of MyLibrary.pm that's being tested and comment out the exit line.
Another complication is that this subroutine calls another one, so we have to take the needs and influence of MyLibrary::printFooter. Fortunately, it's easy to factor out this particular subroutine. If we don't even define the one variable it expects, it executes without complaint and doesn't produce any output.
Furthermore, this subroutine presents new expectations (a database handle and possibly a statement handle) and has other SideEffects than printing output. (As an aside, I would say the main reason I prefer the PythonLanguage over the PerlLanguage is not the executable-line-noise saw, but that Perl is all SideEffects. -- ChrisGray) In the absence of a method for setting up MockObjects for the handles it is possible to set up an empty MySQL database and run some inconsequential SQL statement.
So a working TestCase looks like this
# ---------- tests for &MyLibrary::gracefulExit ----------
package gracefulExit;
use Test::Unit;
require "../MyLibrary.pm";
use CGI;
use DBI;
use IO::String;
sub set_up {
$io = IO::String->new($result);
$old_handle = select($io);
$MyLibrary::output = new CGI("");
$MyLibrary::gDBhandle = DBI->connect("DBI:mysql:mylibrary_test:localhost", \"test", "test");
$MyLibrary::gSth = $MyLibrary::gDBhandle->prepare("show tables");
$MyLibrary::gSth->execute;
}
sub tear_down {
select($old_handle);
$io = undef;
$result = undef;
$old_handle = undef;
$MyLibrary::output = undef;
$MyLibrary::gSth->finish;
$MyLibrary::gDBhandle->disconnect;
$MyLibrary::gSth = undef;
$MyLibrary::gDBhandle = undef;
}
sub test_footer {
my $expected = "