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?


In reply to Eliminating duplicated code in multiple test scripts using Test::More by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.