This came up during a code review today.
In a single directory, my workmate had written a number of
new test scripts, along with a module containing common code
used by the scripts.
To give you a runnable version of the general idea,
here's an example test script, t1.pl:
use strict;
use warnings;
use FindBin ();
use lib "$FindBin::Bin";
use TMod;
use Test::More tests => 5;
ok( 1 == 1, "mytest1" );
TMod::sub1();
ok( 3 == 4, "mytest3" );
ok( 4 == 4, "mytest4" );
where
TMod.pm, in the same directory as the test script, is:
package TMod;
use strict;
use warnings;
use Test::More;
sub sub1
{
ok( 'sub1' eq 'sub99', "sub1-test1" );
ok( 42 == 42, "sub1-test2" );
}
1;
The idea is to factor out common code used in multiple test scripts
into a module in the same directory as the test scripts. An example run:
$ perl t1.pl
1..5
ok 1 - mytest1
not ok 2 - sub1-test1
# Failed test 'sub1-test1'
# at E:/knob/tm/TMod.pm line 9.
ok 3 - sub1-test2
not ok 4 - mytest3
# Failed test 'mytest3'
# at t1.pl line 12.
ok 5 - mytest4
# Looks like you failed 2 tests of 5.
shows it appears to work just fine,
the same
Test::Builder object
being used by
Test::More in both
t1.pl and
TMod.pm.
Though placing the common test code in a module
seems sound to me,
I'm surprised I've never seen it done that way before.
I don't recall seeing any CPAN module with modules containing
Test::More code
in their t/ directory.
If anyone knows of such a CPAN module,
please let us know.
Has anyone used the above approach in their own test code?
Any gotchas to watch out for?
What alternative approaches are there for eliminating
duplicated code in multiple test scripts?