I am practicing to make a new module using Module::Starter. I have written a few test cases for a package, and they run OK sometimes.
However I noticed there are two problems:
-
When the test cases fail, I want put some print statements in the function being tested. I ran
make testand it only tells me that my test cases failed, it does not show my printed output, despite that I am really sure that the print statements are reached. -
Say I have three test cases to test one function, I put a print statement inside the function, when the test cases run, it reports that only 1 out of the three test cases were run. If I remove the print statement, all three test cases will run. Why is that?
Here’s my code:
# package declaration and stuff...
sub get_in {
my ( $hash, @path ) = @_;
my $ref = $hash;
print 'lol'; # This is the troublesome print statement. Remove this statement and all three test cases will run and pass
foreach (@path) {
if ( ref($ref) eq 'HASH' && exists $ref->{$_} ) {
$ref = $ref->{$_};
} else {
return undef;
}
}
return $ref;
}
This is the test cases:
use Test::More tests => 3;
use strict;
use warnings;
use diagnostics;
require_ok('Foo::Doc');
ok( Foo::Doc::get_in( { 'a' => { 'b' => { 'c' => 101 } } }, 'a', 'b', 'c' ) == 101 );
ok( @{ Foo::Doc::get_in( { 'a' => { 'b' => { 'c' => [ 1, 2, 3 ] } } }, 'a', 'b', 'c' ) } == @{ [ 1, 2, 3 ] } );
There are a few problems with you tests that need to be addressed as well as your question itself. First your question:
If you want output to show up in tests, you need to explicitly print to standard error. As a best practice, you also need your output prefaced with
#. The Test::More module provides tools you can use to do this easily.If you don’t want to print that output every time, but only when verbose logging is requested, you can use
note:This is useful when you use
prove -vto run your tests:There’s also an
explainfunction that will dump out complex output for viewing:As for your other problems. It’s generally preferable to use
is()took():Also, when testing complex data structures you need to use
is_deeply()to make a complete comparison:You should definitely take a look at the documentation of Test::More because there’s a great deal of useful information in there.